Ric*_*odd 6 linq nullreferenceexception defaultifempty
我正在寻找解决DefaultIfEmpty()扩展方法在LINQ外连接中使用时不获取空值的问题的解决方案.
代码如下:
var SummaryLossesWithNets = (from g in SummaryLosses
join n in nets
on g.Year equals n.Year into grouping
from x in grouping.DefaultIfEmpty()
select new
{
Year = g.Year,
OEPGR = g.OccuranceLoss,
AEPGR = g.AggregateLoss,
OEPNET = ((x.OEPRecovery == null) ? 0 : x.OEPRecovery),
AEPNET = ((x.AEPRecovery == null) ? 0 : x.AEPRecovery),
});
Run Code Online (Sandbox Code Playgroud)
在List SummaryLosses中,我希望加入到表'nets'中有多年的数据,其中包含多年的子部分.假设x是一个空值,我假设是因为SummaryLosses中的年份与网络中的年份不匹配会在分组列表中创建空值.
如何在这里检查空值?正如您所看到的,我试图在x的属性上检查null,但由于x为null,因此不起作用.
亲切的问候Richard
只需检查是否x为null:
OEPNET = x == null ? 0 : x.OEPRecovery,
AEPNET = x == null ? 0 : x.AEPRecovery
Run Code Online (Sandbox Code Playgroud)
或者,如果x.OEPRecovery也是x.AEPRecovery可以为空的属性,请使用:
OEPNET = x == null ? 0 : (x.OEPRecovery ?? 0),
AEPNET = x == null ? 0 : (x.AEPRecovery ?? 0)
Run Code Online (Sandbox Code Playgroud)