c# - 使用 Linq 求和嵌套值

标签 c# linq lambda

简单问题:我的用户可以有很多订单,也可以有很多产品。获取用户所有 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/

相关文章:

c# - Linq 表到 DataTable 转换

c# - 在 Linq 中选择 column1 的所有不同的最后记录并按 column2 排序(相应地不工作)

c# - Lambda 用法让我感到困惑

haskell - 纯 Haskell Lambda 微积分中列表的仿函数性

c# - 使用SoundPlayer在C#中播放.wav文件

c# - 如何使用 C# 从 winforms 附加数据库

c# - 我需要为 ASP.NET MVC 编写 Ajax 的技巧

c# - 修改linq以获取前5个元素

c# - 如何在 Visual Studio 中生成包含所有属性的 ToString()?

c++ - 如何存储多态闭包?