使用 lambda 和处理 null 的 Linq 2 SQL Sum

标签 linq linq-to-sql

在 Linq to SQL 中使用 sum 和 lambda 时,使用以下代码:

int query = (from f in odc.RDetails
                     where f.ticketID == int.Parse(ticket.ToString())
                     select f).Sum(x => x.Rate);



我收到以下错误:

不能将 null 值分配给 System.Int32 类型的成员,该类型是不可为 null 的值类型。

最佳答案

。您必须确保 x.Rateint,而不是 int? (接受的 int null 作为值)。

。如果查询没有元素,.Sum 将不会执行任何操作并返回 null。选择一个默认值,例如 0

var query = from f in odc.RDetails
            where f.ticketID == int.Parse(ticket.ToString())
            select f;

int result = query.Any() 
             ? query.Sum(x => x.Rate ?? 0) // use the ?? if x.Rate is an "int?".
             : 0; // default value you can choose.

关于使用 lambda 和处理 null 的 Linq 2 SQL Sum,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10708677/

相关文章:

c# - ASP.NET Core 5 Blazor WASM、gRPC、Entity Framework Core 5 : many-to-many results in stack overflow

c# - 什么是 LINQ/Lambda 等价于 Select Count(*), SUM(someColumn) From SomeTable

c# - 如何从 Expression<Func<MyClass, string>> 动态创建 Expression<Func<MyClass, bool>> 谓词?

c# - 在一个 LINQ 查询中获取两列的总和

linq - 在 LINQ 查询中删除多条记录的最佳方法?

c# - 使用列表作为 LINQ to SQL 查询的条件

C# Linq 到 SQL :cannot add an entity that already exists

c# - 在LINQ查询中动态设置表名

c# - 报告一百万行的最佳方法

c# - 将 NULL 值传递给 LINQ 中的日期时间字段