用Linq求和嵌套值 [英] Sum nested values with Linq
问题描述
一个简单的问题:我的用户可以拥有很多订单,而这些订单可以拥有很多产品. Linq(lambda)查询看起来像什么,以获取用户的所有Product.Price值的总计?
Simple problem: I have Users that can have many Orders that can have many Products. What does the Linq (lambda) query look like to get a User's grand total of all Product.Price values?
我已经尝试过了:
int total = users.Sum(u => u.Orders.Sum(o => o.Products.Sum(p => p.Price)));
但这给了我
强制转换为值类型'Int32',因为实例化值为null.结果类型的通用参数或查询必须使用可为空的类型.
The cast to value type 'Int32' failed because the materialized value is null. Either the result type's generic parameter or the query must use a nullable type.
当然,用户可能没有任何订单,并且订单可能没有任何产品.但是Product.Price不是可为空的值.
Of course, a user may not have any orders, and an order may not have any products. But Product.Price is not a nullable value.
所以我尝试了这个,以为它使空的收藏感到窒息:
So I tried this, thinking it was choking on empty collections:
int total = users.Sum(u => u.Orders.Sum(o => o.Products.Sum(p => p.Price) ?? 0) ?? 0) ?? 0;
但这会引发编译错误,表示??
的左侧不可为空.
But it's throwing compile errors, saying the left side of the ??
is not nullable.
我在做什么错了?
谢谢.
更新:在我的示例中使用了马克的逻辑后,上述示例的工作版本:
UPDATE: A working version of my examples above after using Marc's logic from his answer:
int total = users.Sum(u => u.Orders.Sum(o => o.Products.Sum(p => (int?)p.Price))) ?? 0;
推荐答案
int total = (from user in users
from order in user.Orders
from product in order.Products
select (int?)product.Price).Sum() ?? 0;
将是我的奉献;有一个令人烦恼的小故障,即SQL中超过0行的SUM是NULL
而不是0
-上面的方法可以解决此问题.
would be my offering; there is an annoying glitch that the SUM in SQL over 0 rows is NULL
, not 0
- the above works around that.
或作为lambdas(来自评论):
or as lambdas (from comments):
int total = users.SelectMany(user => user.Orders)
.SelectMany(order => order.Products)
.Sum(product => (int?)product.Price) ?? 0;
这篇关于用Linq求和嵌套值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!