【问题标题】:get count of all the grouped items in all groups from IEnumerable<IGrouping<TKey, TSource>> GroupBy从 IEnumerable<IGrouping<TKey, TSource>> GroupBy 获取所有组中所有分组项的计数
【发布时间】:2019-10-24 05:37:08
【问题描述】:

我使用 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 而不必遍历每个组来迭代计数器?

【问题讨论】:

    标签: c# linq ienumerable igrouping


    【解决方案1】:

    最简单的方法就是Sum

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

    可能有一天,您只需要计算不同的水果(如果某些水果可能属于不同的组)。那就有点难了。

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

    SelectMany 将您的分组变量“转换”为简单的行 IEnumarable,您可以将其用作通用列表。

    【讨论】:

      猜你喜欢
      • 2012-08-14
      • 1970-01-01
      • 2021-06-07
      • 2019-08-03
      • 2017-08-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多