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.)
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.
You can use the Aggregate extension:
string s = list.Aggregate<int, string>(String.Empty, (x, y) => (x.Length > 0 ? x + "^" : x) + y.ToString());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With