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?
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].
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).
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.
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());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With