LINQ: How do I concatenate a list of integers into comma delimited string?

前端 未结 4 1417
鱼传尺愫
鱼传尺愫 2021-02-01 13:51

It\'s probably something silly I missed, but I try to concatenate a list of integers instead of summing them with:

integerArray.Aggregate((accumulator, piece) =&         


        
相关标签:
4条回答
  • 2021-02-01 14:05

    Which version of .NET? In 4.0 you can use string.Join(",",integerArray). In 3.5 I would be tempted to just use string.Join(",",Array.ConvertAll(integerArray,i=>i.ToString())); (assuming it is an array). Otherwise, either make it an array, or use StringBuilder.

    0 讨论(0)
  • 2021-02-01 14:10

    The error you are getting is because you didn't use the override of Aggregate which lets you specify the seed. If you don't specify the seed, it uses the type of the collection.

    integerArray.Aggregate("", (accumulator, piece) => accumulator + "," + piece);
    
    0 讨论(0)
  • 2021-02-01 14:12

    You probably want to use String.Join.

    string.Join(",", integerArray.Select(i => i.ToString()).ToArray());
    

    If you're using .Net 4.0, you don't need to go through the hassle of reifying an array. and can just do

     string.Join(",", integerArray);
    
    0 讨论(0)
  • 2021-02-01 14:13

    Just to add another alternative to @Marc's

    var list = string.Join( ",", integerArray.Select( i => i.ToString() ).ToArray() );
    
    0 讨论(0)
提交回复
热议问题