Here's the scenario: we have a Silverlight application with a UIElement that binds to an IEnumerable of type string where the contents of each item is an error or validation message. There are times when instead of binding to the list I just want a concatenated string of all the items in the collection with a CRLF stuck on the end of each. Just for kicks I asked my friend Nick what at the time felt like a silly "how many convoluted ways can you think of to solve this simple programming problem, and how would you do it in LINQ?" question and, being the genius that he is, he suggested using the Aggregate extension method.
I already had a passing awareness of .Aggregate() but to be honest it hadn't occurred to me that it would be useful for something other than aggregating numbers, and at any rate I found it a bit unintuitive to use initially. It turns out, of course, that the accumulator can work on a series of strings just as easily as, say, ints, and it really couldn't be much simpler.
Here's how it looks as a C# Statement in LinqPad:
string[] words = { "foo", "bar", "ski" };
words.Aggregate(string.Empty, (seed, w) => seed + "\r\n" + w).Dump();
And in the Results pane:
foo
bar
ski
Pretty slick!
3 comments:
var words = new string[] { "foo", "bar", "ski" };
//Assuming we want the same results as this:
var expected = string.Join(Environment.NewLine, words).Dump("Using string.Join");
//But we get an extra-newline at the end:
var actual = words.Aggregate(new StringBuilder(), (seed, w)=>seed.AppendLine(w), seed=>seed.ToString()).Dump("Using Enumerable.Aggregate");
System.Diagnostics.Debug.Assert(expected == actual, "Fail!");
//This is really visible when joining with "," instead of "newline"
words.Aggregate(new StringBuilder(), (seed, w)=>seed.Append(w+","), seed=>seed.ToString()).Dump("Using Enumerable.Aggregate, has trailing comma!");
//Fixed
words.Aggregate(new StringBuilder(), (seed, w)=>seed.Append(seed.Length==0?w:","+w), seed=>seed.ToString()).Dump("No trailing comma");
Grynn -- nice additions; I was looking solely at the Aggregate() method itself and didn't bother refining my code.
Better yet (and better late than never :-) ):
string.Join(",\r\n", words).Dump();
results:
foo,
bar,
ski
Post a Comment