tags:

views:

176

answers:

4

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?

+9  A: 

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.

Marc Gravell
would it not always be best perf wise to use a StringBuilder in this case?
Damien McGivern
Oddly enough, the Join is more performant that the StringBuilder. I did a test, and with an array 1,000,000 in size, Join took 207ms, while StringBuilder took 264ms. I suspect this is because the Join is optimized for the task, whereas the SB is optimized more for the general case.
Cyberherbalist
+4  A: 

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);
Samuel
+1 because you answered the question. However, your code has O(n^2) performance. Not cool.
Kennet Belenky
now count the number of strings involved...
Marc Gravell
+1  A: 

Just to add another alternative to @Marc's

var list = string.Join( ",", integerArray.Select( i => i.ToString() ).ToArray() );
tvanfosson
+1  A: 

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);
48klocs
Slick! Really helpful.
Cyberherbalist