[英]linq count group only if all items in group are 'true'
Given the sample data below, I need a linq query that returns the number of items that are in stock at all 3 warehouses. 给定下面的示例数据,我需要一个linq查询,该查询返回所有3个仓库中库存物品的数量。 In the example below, it should return
2
, because only skus ABC-123
and JKL-789
are ins stock at all 3 warehouses. 在下面的示例中,它应该返回
2
,因为在所有3个仓库中只有skus ABC-123
和JKL-789
是ins库存。 But my query is returning 3? 但是我的查询返回3?
WarehouseId Sku InStock
===================================
1 ABC-123 true
2 ABC-123 true
3 ABC-123 true
1 XYZ-789 true
2 XYZ-789 false
3 XYZ-789 true
1 JKL-456 true
2 JKL-456 true
3 JKL-456 true
int inStock = query.Where(x => x.InStock).GroupBy(x => x.Sku).Count();
Your query returns 3 because your Count()
is unrestricted, meaning that it counts all groups, not only the ones with all items present in stock. 您的查询返回3,因为您的
Count()
是不受限制的,这意味着它对所有组进行计数,而不仅仅是对所有库存中存在的组进行计数。
Add a condition with a call to All(item => item.InStock)
to count only the items that you need: 通过调用
All(item => item.InStock)
添加条件以仅计算所需的项目:
var inStock = query
.GroupBy(x => x.Sku)
.Count(g => g.All(item => item.InStock));
Note that Where
is now gone, so that all items are included in groups. 请注意,现在
Where
去了,以便所有项目都包含在组中。
int inStock = query
.Where(x => x.InStock)
.GroupBy(x => x.Sku)
.Where(g=>g.Count() == 3)
.Count();
Althought dasblinkenlight solution is better, as it covers adding new warehouses. 尽管dasblinkenlight解决方案更好,因为它包括添加新仓库。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.