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

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

问题描述

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

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

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

如果所有 d.DurationMonths 值为空,则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;

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

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