Using LINQ to Reduce Collections

15 July 2009 | Scott Williams | .NET 3.5, LINQ

Recently, I had a Dictionary<string, string> object that I wanted to display as a single string, essentially like “[key1] => value1  [key2] => value2” and so on. Back in the olden days of .NET 2.0 and prior, you could have just done it like this:

string s = ""; // Or a StringBuilder
foreach (string key in dict.Keys) {
    s += string.Format("[{0}] => {1}  ", key, dict[key]);
}

This was my first thought to solve the issue, but I wasn’t exactly thrilled with it. I knew that in Python this would be a relatively simple reduce (as in Map/Reduce) operation and could be done on one line.

I thought that there must be a similar way using LINQ to get a one-liner. There is no Extension Method called “Reduce,” but the equivalent is Aggregate. The only catch is that for the Aggregate function, the generic accumulator type must be the same as what is in the dictionary, which in this case was a key/value pair.

The solution is still technically a one liner, but I split it up for readability’s sake. You can use Select to munge the pair into a single string.

IDictionary foo; // Fill foo in here
string prettyPrint = foo.
    Select(pair => string.Format("[{0}] => {1} ", pair.Key, pair.Value)).
    Aggregate((acc, s) => acc += s);

If you have a bit of a Functional programming background, this makes sense, though if you do not, it may not be as readable.

Comments are closed.