Amount using Linq in <List <Dictionary <string, int >>

I have a generic list declared like this:

List<Dictionary<string, int>> sales; 

The string will be the product name, and int the number of units sold. I want to group by product name and summarize total sales. Therefore, I can see the number of units sold for each product.

How can I do this with linq?

Thanks!

+2
source share
1 answer

This will give you the result in the form of a dictionary, where the key is the name of the product 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 
+10
source

Source: https://habr.com/ru/post/957446/


All Articles