Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Aggregate a List<int> to a string using (i, j) => i + "delimiter" + j [duplicate]

Tags:

c#

linq

I'm triyng to do a quick Haskell-like aggregation in Linq (C#), to turn a List into a string in the format "i^j^k..." etc.

is this possible in one query, or should I just do it the old-fasioned

foreach (int i in list)
{
     string+= i + "^"
}

(p.s. yes, that's pseudocode and wouldn't compile.)

like image 640
Ed James Avatar asked Sep 15 '09 16:09

Ed James


2 Answers

Use string.Join:

string.Join("^", list.Select(x => x.ToString()).ToArray())

In this particular case it may be more efficient to use StringBuilder directly as Append(int) may avoid creating the temporary strings. Unless this turns out to be a bottleneck, however, I'd stick to this simple single expression.

like image 90
Jon Skeet Avatar answered Nov 10 '22 23:11

Jon Skeet


You can use the Aggregate extension:

string s = list.Aggregate<int, string>(String.Empty, (x, y) => (x.Length > 0 ? x + "^" : x) + y.ToString());
like image 30
Guffa Avatar answered Nov 11 '22 00:11

Guffa