我有一个List<User>
集合,我想使用User.Id属性创建一个逗号分隔的字符串,所以:
"12321,432434,123432452,1324234"
我是用循环完成的,但是希望有人能告诉我linq方式吗?
答案 0 :(得分:93)
在.NET 4中:
string joined = string.Join(",", list.Select(x => x.Id));
在.NET 3.5中:
string joined = string.Join(",", list.Select(x => x.Id.ToString()).ToArray());
不同之处在于.NET 4's overload list for string.Join
比the one in .NET 3.5宽,overload you really want是“新”之一:
public static string Join<T>(string separator, IEnumerable<T> values)
你仍然可以在.NET 2.0中使用,只使用List<T>
特定的方法而不是LINQ(我假设你仍然可以使用C#3):
string joined = string.Join(",", list.ConvertAll(x => x.Id.ToString())
.ToArray());
答案 1 :(得分:1)
鉴于此清单:
List<User> users = (GetUsers() ?? new List<User>())
.Where(u => u != null).ToList();
// no more nulls
.NET 3.5 - String.Join
Join(String,String())
Join(String,String(),Int32,Int32)
示例:强>
return string.Join(",", users.Select(u => u.Id.ToString()).ToArray());
.NET 4.0 - String.Join
Join(String,IEnumerable(Of String))
Join(Of T)(String,IEnumerable(Of T))
加入(String,Object())//真的吗?加入“东西”?
Join(String,String())
Join(String,String(),Int32,Int32)
示例强>
return string.Join(",", users.Select(u => u.Id));
答案 2 :(得分:0)
使用
string myResult = string.Join (",", (from l in myList select l.ID.ToString()).ToArray());
答案 3 :(得分:0)
string.Join( ",", list.Select( item => item.ID ).ToArray() );