Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I get the sum of the Counts of nested Lists in a Dictionary without using foreach?

I want to get the total number of items in the Lists in the following Dictionary:

Dictionary<int, List<string>> dd = new Dictionary<int, List<string>>() {
    {1, new List<string> {"cem"}},
    {2, new List<string> {"cem", "canan"}},
    {3, new List<string> {"canan", "cenk", "cem"}}
};

// This only returns an enumerated array.
var i = (from c in dd
         select c.Value.Count).Select(p=>p);
like image 699
uzay95 Avatar asked Jul 23 '09 14:07

uzay95


3 Answers

I believe this will get you the count you want efficiently and clearly. Under the hood it has to iterate through the lists, but to get a total count, there is no way to avoid this.

var i = dd.Values.Sum(x => x.Count);
like image 186
Timothy Carter Avatar answered Nov 04 '22 09:11

Timothy Carter


var i = dd.Values.SelectMany(v => v).Count();
like image 2
Yuriy Faktorovich Avatar answered Nov 04 '22 09:11

Yuriy Faktorovich


Total count of all list items:

dd.SelectMany(i => i.Value).Count();

List containing individual list counts:

dd.Select(i => i.Value.Count).ToList()
like image 2
John Rasch Avatar answered Nov 04 '22 07:11

John Rasch