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

前端 未结 4 1932
[愿得一人]
[愿得一人] 2020-12-24 01:21

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

\"12321,432434,123432452,132         


        
4条回答
  •  伪装坚强ぢ
    2020-12-24 01:55

    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(string separator, IEnumerable values)
    

    You can still do it in .NET 2.0, just using a List-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());
    

提交回复
热议问题