How to convert a List into a comma-separated list, using the class’s Id property as the value

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

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)