Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use List.ToLookup()

Tags:

c#

.net

linq

I have a List like the following:

var products = new List<Product>
{
    new Product { Id = 1, Category = "Electronics", Value = 15.0 },
    new Product { Id = 2, Category = "Groceries", Value = 40.0 },
    new Product { Id = 3, Category = "Garden", Value = 210.3 },
    new Product { Id = 4, Category = "Pets", Value = 2.1 },
    new Product { Id = 5, Category = "Electronics", Value = 19.95 },
    new Product { Id = 6, Category = "Pets", Value = 5.50 },
    new Product { Id = 7, Category = "Electronics", Value = 250.0 },
};

I want to group by category and get the sum of 'Values' belonging to that category.. Example: Electronics: 284.95

While I can do this in some other way, I want to learn usage of Look-Up.

Is it possible to get these 2 values (category and Value) in a Look-Up? If yes, How can I do that?

like image 201
ViV Avatar asked Apr 18 '13 05:04

ViV


2 Answers

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)); 
like image 170
TheEvilPenguin Avatar answered Oct 16 '22 10:10

TheEvilPenguin


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);
}
like image 9
Alastair Pitts Avatar answered Oct 16 '22 11:10

Alastair Pitts