“我有一个具有属性”CustomizationName“的对象列表。
我想用逗号加入该属性的值,即;像这样的东西:
List<MyClass> myclasslist = new List<MyClass>();
myclasslist.Add(new MyClass { CustomizationName = "foo"; });
myclasslist.Add(new MyClass { CustomizationName = "bar"; });
string foo = myclasslist.Join(",", x => x.CustomizationName);
Console.WriteLine(foo); // outputs 'foo,bar'
答案 0 :(得分:27)
string foo = String.Join(",", myClasslist.Select(m => m.CustomizationName).ToArray());
如果需要,可以将其转换为扩展方法:
public static class Extensions
{
public static string ToDelimitedString<T>(this IEnumerable<T> source, Func<T, string> func)
{
return ToDelimitedString(source,",",func);
}
public static string ToDelimitedString<T>(this IEnumerable<T> source, string delimiter, Func<T, string> func)
{
return String.Join(delimiter, source.Select(func).ToArray());
}
}
用法:
public class MyClass
{
public string StringProp { get; set; }
}
.....
var list = new List<MyClass>();
list.Add(new MyClass { StringProp = "Foo" });
list.Add(new MyClass { StringProp = "Bar" });
list.Add(new MyClass { StringProp = "Baz" });
string joined = list.ToDelimitedString(m => m.StringProp);
Console.WriteLine(joined);