Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

linq

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 was hoping someone could show me the linq way?

like image 896
codecompleting Avatar asked Sep 28 '11 19:09

codecompleting


People also ask

How do you convert a list to a comma-separated string in Python?

How to Convert a Python List into a Comma-Separated String? You can use the . join string method to convert a list into a string. So again, the syntax is [seperator].

How do you separate comma-separated values in a list Python?

You can use the str. split method. Careful though, splitting an empty string does not return what one might have expected: "". split(",") returns [""] (a list with one element, which is empty string).

How do I create a comma-separated string from a list of strings in C#?

The standard solution to convert a List<string> to a comma-separated string in C# is using the string. Join() method. It concatenates members of the specified collection using the specified delimiter between each item.


1 Answers

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()); 
like image 172
Jon Skeet Avatar answered Sep 27 '22 20:09

Jon Skeet