如果求和值全部为空,如何使 linq Sum 返回 null [英] How to make a linq Sum return null if the summed values are all null

查看:35
本文介绍了如果求和值全部为空,如何使 linq Sum 返回 null的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个看起来像这样的 LINQ 查询...

I have a LINQ query that looks like this...

var duration = Level3Data.AsQueryable().Sum(d => d.DurationMonths);

如果所有 d.DurationMonths 值为 null,则 Sum 返回 0.如果所有 d.DurationMonths 都是 null,如何使 Sum 返回 null?还是我需要先运行一个单独的查询来消除这种情况,然后再执行求和?

If all the d.DurationMonths values are null the Sum returns 0. How can I make the Sum return null if all the d.DurationMonths are null? Or do I need to run a separate query first to eliminate this situation before performing the sum?

推荐答案

除了前面关于扩展方法的建议 - 你可以使用三元运算符...

Along with the previous suggestion for an extension method - you could use a ternary operator...

var duration = Level3Data.AsQueryable().Any(d => d.DurationMonths.HasValue) 
               ? Level3Data.AsQueryable().Sum(d => d.DurationMonths) 
               : null;

这篇关于如果求和值全部为空,如何使 linq Sum 返回 null的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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