Use List.ToLookup()

When you retrieve by key from a Lookup, it behaves just like a grouping, so you can do things like this:

var productLookup = products.ToLookup(p => p.Category);
var electronicsTotalValue = productLookup["Electronics"].Sum(p => p.Value);
var petsTotalValue = productLookup["Pets"].Sum(p => p.Value);
//etc

var totalValue = products.Sum(p => p.Value);
// I wouldn't use the Lookup here, the line above makes more sense and would execute faster
var alsoTotalValue = productLookup.Sum(grp => grp.Sum(p => p.Value)); 

You probably want to use ToDictionary() instead of ToLookup

var dict = products
    .GroupBy(p => p.Category)
    .ToDictionary(grp => grp.Key, grp => grp.Sum(p => p.Value));

foreach(var item in dict)
{
    Console.WriteLine("{0} = {1}", item.Key, item.Value);
}

Tags:

C#

.Net

Linq