tags:

views:

30

answers:

1

Hi All,

I have a generic list declared as so:

List<Dictionary<string, int>> sales;

The string will be a product name and the int the number of units sold. I want to group by productname and sum the total sales. So i can see the number of units sold for each product.

How would i do this using linq?

Thanks!

+4  A: 

This will give you the result as a dictionary where the key is the product name and the value is the total number of units sold.

var result =
    sales.SelectMany(d => d)                        // Flatten the list of dictionaries
         .GroupBy(kvp => kvp.Key, kvp => kvp.Value) // Group the products
         .ToDictionary(g => g.Key, g => g.Sum());   // Sum each group
Mark Byers
Compile error : System.Collections.Generic.List<System.Collections.Generic.Dictionary<string,int>>' does not contain a definition for 'SelectMany'
Pete
@Pete: Ensure you have `using System.Linq;` at the top of the file. And you *are* using .NET 3.5, right? Because it won't work in older versions of .NET... LINQ was added in .NET 3.5.
Mark Byers