Linq错误通用参数,否则查询必须使用可为空的类型
问题描述:
在LINQ中使用求和函数时出现此错误:
I got this error when i use sum function in LINQ:
强制转换为值类型十进制"失败,因为实例化值为null.结果类型的通用参数或查询必须使用可为空的类型.
The cast to value type 'Decimal' failed because the materialized value is null. Either the result type's generic parameter or the query must use a nullable type.
GroupProduct.Where(a => a.Product.ProductID==1).Sum(Content => Content.Amount==null?0:Content.Amount),
答
这是我通常使用的方法.这将涵盖Amount
为空的可能性,也将涵盖空集的可能性.
This is what I usually use. This will cover the possibility of Amount
being null and also cover the possibility of an empty set.
GroupProduct.Where(a => a.Product.ProductID == 1)
.Select(c => c.Amount ?? 0) // select only the amount field
.DefaultIfEmpty() // if selection result is empty, return the default value
.Sum(c => c)
DefaultIfEmpty()
返回与Amount
的类型关联的默认值int
,在这种情况下默认值为0
.
DefaultIfEmpty()
returns the default value associated with Amount
's type, which is int
, in which case the default value is 0
.