One little known and scarcely document feature of LINQ is its Aggregate method. This function is very useful when you want to do something to the whole collection.

Lets say I have the follwoing BlogEntry class

public class BlogEntry  
{ 
    public Tags { get; set; } 
}

Now what do I do if I want to build a tag cloud?

I can use a dictionary and loop through like so:

var entries = GetBlogEntries();
Dictionary<string, int> tags = new Dictionary<string, int>();
foreach (BlogEntry entry in entries)
{
    foreach (string tag in entry.Tags)
    {
        if (!tags.ContainsKey(tag)) 
            tags.Add(tag, 0); 
        tags[tag]++; 
    } 
}

But the easier way is to use the built in Aggregate extension method

return entries.Aggregate(new Dictionary<string, int>(), (tags, e) 
{ 
        if (!tags.ContainsKey(tag)) 
            tags.Add(tag, 0); 
        tags[tag]++; 
        return tags;    
}

Comment