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如果使用其他类型可以实现相同的目标,则不必是字符串.我认为你正在寻找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任何非字符串值.
| 归档时间: |
|
| 查看次数: |
395 次 |
| 最近记录: |