开发者

How to convert a List<T> into a comma-separated list, using the class's Id property as the value

开发者 https://www.devze.com 2023-04-08 05:13 出处:网络
I have a List<User> collection, and I want to create a comma seperated string using the User.Id property, so:

I have a List<User> collection, and I want to create a comma seperated string using the User.Id property, so:

"12321,432434,123432452,1324234"

I have done it using a loop, but开发者_StackOverflow社区 was hoping someone could show me the linq way?


In .NET 4:

string joined = string.Join(",", list.Select(x => x.Id));

In .NET 3.5:

string joined = string.Join(",", list.Select(x => x.Id.ToString()).ToArray());

The difference is that .NET 4's overload list for string.Join is wider than the one in .NET 3.5, and the overload you really want is one of the "new" ones:

public static string Join<T>(string separator, IEnumerable<T> values)

You can still do it in .NET 2.0, just using a List<T>-specific method instead of LINQ (I'm assuming you can still use C# 3):

string joined = string.Join(",", list.ConvertAll(x => x.Id.ToString())
                                     .ToArray());


string.Join( ",", list.Select( item => item.ID ).ToArray() );


use

string myResult = string.Join (",", (from l in myList select l.ID.ToString()).ToArray());


Given this list:

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)

Example:

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))

Join(String, Object()) // really? Just joining "stuff"?

Join(String, String())

Join(String, String(), Int32, Int32)

Example

return string.Join(",", users.Select(u => u.Id));
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号