Search code examples
c#linqienumerableigrouping

get count of all the grouped items in all groups from IEnumerable<IGrouping<TKey, TSource>> GroupBy


I have grouped together fruits by certain common properties (weight, color, etc) using LINQ GroupBy,

and then I have done some processing that removes some groups from that list of IGroupings (together with all the fruits in that group).

Now, I would like to find out (thru LINQ maybe) the sum of all the fruits I have in all the groups left from the process that is in that IEnumerable> groupedFruits..

How do I do that?

I do not want to know how many groups I have.. But, I want to know how many fruits I have in all those groups

List<Fruit> fruits = getAllKindsOfFruits(); //maybe I get 1,000 fruits here

var groupsOfFruits= fruits.GroupBy(x => new { x.color, x.weight, x.type });

//
//<some process of narrowing down here, removing some groups of fruits that are disqualified>
//

//Here I want to count how many fruits are left, regardless of which group they belong to, maybe I get //just 300 fruits as a result

Is there a way to do this with just LINQ and not have to loop thru each of the groups to iterate a counter?


Solution

  • The simpliest way is just Sum.

    groupsOfFruits.Sum(group => group.Count());
    

    Maybe some day you will need to count only distinct fruits (if some fruit may be in different groups). Then it will be a bit harder.

    groupsOfFruits.SelectMany(group => group)
                  .Distinct()
                  .Count();
    

    SelectMany "converts" your grouping variable into simple line IEnumerable which you can use as a common list.