简体   繁体   中英

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?

The simpliest way is just Sum .

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

May be 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 IEnumarable which you can use as a common list.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM