簡體   English   中英

從 IEnumerable 獲取所有組中所有分組項的計數<igrouping<tkey, tsource> &gt; 分組依據</igrouping<tkey,>

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

我使用 LINQ GroupBy 將水果按某些常見屬性(重量、顏色等)分組在一起,

然后我做了一些處理,從 IGroupings 列表中刪除了一些組(連同該組中的所有水果)。

現在,我想找出(通過 LINQ 可能)我在 IEnumerable> groupedFruits 中的過程留下的所有組中的所有水果的總和。

我怎么做?

我不想知道我有多少組。但是,我想知道我在所有這些組中有多少水果

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

有沒有辦法只用 LINQ 而不必遍歷每個組來迭代計數器?

最簡單的方法就是Sum

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

可能有一天,您只需要計算不同的水果(如果某些水果可能屬於不同的組)。 然后會有點難。

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

SelectMany將您的分組變量“轉換”為簡單的IEnumarable行,您可以將其用作通用列表。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM