gpt4 book ai didi

c# - 使用 Linq 求和嵌套值

转载 作者:可可西里 更新时间:2023-11-01 08:16:32 25 4
gpt4 key购买 nike

简单问题:我的用户可以有很多订单,也可以有很多产品。获取用户所有 Product.Price 值的总计的 Linq (lambda) 查询是什么样的?

我已经试过了:

int total = users.Sum(u => u.Orders.Sum(o => o.Products.Sum(p => p.Price)));

但它给了我:

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 不是可以为 null 的值。

所以我尝试了这个,认为它被空集合窒息了:

int total = users.Sum(u => u.Orders.Sum(o => o.Products.Sum(p => p.Price) ?? 0) ?? 0) ?? 0;

但它抛出编译错误,说 ?? 的左侧不可为空。

我做错了什么?

提前致谢。

更新:在使用 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;

将是我的奉献;有一个恼人的故障,即 SQL 中超过 0 行的 SUM 是 NULL,而不是 0 - 上面解决了这个问题。

或作为 lambda(来自评论):

int total = users.SelectMany(user => user.Orders)
.SelectMany(order => order.Products)
.Sum(product => (int?)product.Price) ?? 0;

关于c# - 使用 Linq 求和嵌套值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5893445/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com