[英]Sum nested values with Linq
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?
Linq (lambda) 查询如何获取用户的所有 Product.Price 值的总计?
I've tried this:我试过这个:
int total = users.Sum(u => u.Orders.Sum(o => o.Products.Sum(p => p.Price)));
But it's giving me:但它给了我:
The cast to value type 'Int32' failed because the materialized value is null.
转换为值类型“Int32”失败,因为具体化值为 null。 Either the result type's generic parameter or the query must use a nullable type.
结果类型的泛型参数或查询必须使用可为空的类型。
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.
但是 Product.Price 不是可以为空的值。
So I tried this, thinking it was choking on empty collections:所以我尝试了这个,认为它被空的 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.不可为空。
What am I doing wrong?我究竟做错了什么?
Thanks in advance.提前致谢。
UPDATE: A working version of my examples above after using Marc's logic from his answer:更新:使用 Marc 的回答中的逻辑后,我上面的示例的工作版本:
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;
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.有一个恼人的故障是 SQL 超过 0 行的 SUM 是
NULL
,而不是0
- 上面的解决方法。
or as lambdas (from comments):或作为 lambdas(来自评论):
int total = users.SelectMany(user => user.Orders)
.SelectMany(order => order.Products)
.Sum(product => (int?)product.Price) ?? 0;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.