连接<t>(List <t>列表,字符串specifiedPropertyOfT)?</t> </t>

时间:2011-10-27 15:32:45

标签: c# linq generics reflection collections

从参数到属性?

public class ConcatenateListTMember
{
    public static void Test()
    {
        var someList = new List<AnyClass>();
        someList.Add(new AnyClass("value1"));
        someList.Add(new AnyClass("value2"));
        Console.WriteLine(Concatenate(someList, "SomeProperty"));
        Console.ReadLine();
    }

    static string Concatenate<T>(List<T> list, string specifiedPropertyOfT)
    {
        string output = String.Empty;
        // TODO: Somehow concatenate all the specified property elements in the list?
        return output;
    }
}

internal class AnyClass
{
    public AnyClass(string someProperty)
    {
        SomeProperty = someProperty;
    }

    public string SomeProperty { get; set; }
}

如何在此代码示例中实现泛型方法?

  • 请注意,如果使用其他类型可以实现相同的目标,则specifiedPropertyOfT不必是字符串。
  • 理想情况下,不需要反思:)

3 个答案:

答案 0 :(得分:5)

我认为你正在寻找.NET 4中string.Join的新重载,它允许:

IEnumerable<AnyClass> sequence = ...;
string joined = string.Join(",", sequence.Select(x => x.SomeProperty));

如果你不能使用lambda表达式来表达属性 - 例如因为这必须在执行时完成 - 那么必须使用反射。

请注意Select中的选择器不必返回字符串 - String.Join会在任何非字符串值上调用ToString

答案 1 :(得分:1)

更好 - 扩展方法:

static string Concatenate<T>(this IEnumerable<T> list, Func<T,string> func)
{
    return String.Join("",list.Select(func));
}

用法:

someList.Concatenate(i => i.SomeProperty);

实例:http://rextester.com/runcode?code=LRA78268

答案 2 :(得分:1)

尝试这样的事情。我在IEnumerable上创建了一个扩展方法:

public static class Extension
{
    public static string ConcatinateString<T>(this IEnumerable<T> collection, Func<T, string> GetValue)
    {
        StringBuilder sb = new StringBuilder();
        foreach (var item in collection)
        {
            sb.Append(GetValue(item));
        }
        return sb.ToString();
    }
}

然后如此称呼它,你会使用这样的东西:

var values = new List<TestClass>
        {
            new TestClass(){Name="John",Comment="Hello"},
            new TestClass(){Name="Smith", Comment="Word"}
        };
string s = values.ConcatinateString((x => x.Name));
string v = values.ConcatinateString((x => x.Comment));

在此示例s = "JohnSmith"v = "HelloWord"中。 Func()为您提供了灵活性。你基本上告诉函数去哪里获取字符串连接。如果你正在使用长集合,我也使用了StringBuilder。