Search code examples
c#linqaggregate

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


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) => accumulator+"," + piece)

The compiler complained about argument error. Is there a slick way to do this without having to go through a loop?


Solution

  • 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.