Linq错误通用参数,否则查询必须使用可为空的类型 [英] Linq error generic parameter or the query must use a nullable type

查看:54
本文介绍了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.

这篇关于Linq错误通用参数,否则查询必须使用可为空的类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆