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

Cel*_*Cel 0 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; }
}
Run Code Online (Sandbox Code Playgroud)

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

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

Jon*_*eet 5

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

IEnumerable<AnyClass> sequence = ...;
string joined = string.Join(",", sequence.Select(x => x.SomeProperty));
Run Code Online (Sandbox Code Playgroud)

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

请注意,选择器in Select不必返回字符串 - String.Join将调用ToString任何非字符串值.