如何做的LINQ聚集时,有可能是一个空集? [英] How to do Linq aggregates when there might be an empty set?

查看:93
本文介绍了如何做的LINQ聚集时,有可能是一个空集?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

的东西,其中的事情的LINQ的集合都有一个金额(十进制)财产



我试图做一个汇总在这个物联网的某些子集:

  VAR总= myThings.Sum(T => t.Amount); 

和这很好地工作。但后来我又说,给我留下了在结果没有事情的条件:

  VAR总= myThings.Where(T => ; t.OtherProperty == 123).SUM(T => t.Amount); 

和而不是得到总= 0或空的,我得到一个错误:




System.InvalidOperationException:空值不能分配给System.Decimal类型
A件,它是一个非空值类型




这是真的急了,因为我没想到的是行为。我本来期望总为零,也许空 - !但肯定不是抛出一个异常



我在做什么错了?有什么解决方法/修复

修改 - 例如



感谢所有为你的评论。下面是一些代码,复制并粘贴(不是简单)。这是LinqToSql(也许这就是为什么你不能重现我的问题):

  VAR索赔= Claim.Where(CL => cl.ID℃下); 
变种数= claims.Count(); //计数= 0
VAR总和= claims.Sum(CL => cl.ClaimedAmount); //抛出异常


解决方案

我可以用你的重现问题下面对罗斯文LINQPad查询:

  Employees.Where(E => e.EmployeeID == -999).SUM(E = GT; e.EmployeeID)

这里有两个问题:




  1. 总和()

  2. LINQ到SQL如下SQL语义过载,不是C#语法。



在SQL中, SUM(没有行)收益,不是零。但是,对于您的查询的类型推断为您提供了小数类型的参数,而不是小数?。解决方法是帮助类型推断选择正确的类型,例如:

  Employees.Where(E => e.EmployeeID = = -999).SUM(E =>(INT)e.EmployeeID)

现在的正确的总和()超载将被使用。


I have a Linq collection of Things, where Thing has an Amount (decimal) property.

I'm trying to do an aggregate on this for a certain subset of Things:

var total = myThings.Sum(t => t.Amount);

and that works nicely. But then I added a condition that left me with no Things in the result:

var total = myThings.Where(t => t.OtherProperty == 123).Sum(t => t.Amount);

And instead of getting total = 0 or null, I get an error:

System.InvalidOperationException: The null value cannot be assigned to a member with type System.Decimal which is a non-nullable value type.

That is really nasty, because I didn't expect that behavior. I would have expected total to be zero, maybe null - but certainly not to throw an exception!

What am I doing wrong? What's the workaround/fix?

EDIT - example

Thanks to all for your comments. Here's some code, copied and pasted (not simplified). It's LinqToSql (perhaps that's why you couldn't reproduce my problem):

var claims = Claim.Where(cl => cl.ID < 0);
var count = claims.Count(); // count=0
var sum = claims.Sum(cl => cl.ClaimedAmount); // throws exception

解决方案

I can reproduce your problem with the following LINQPad query against Northwind:

Employees.Where(e => e.EmployeeID == -999).Sum(e => e.EmployeeID)

There are two issues here:

  1. Sum() is overloaded
  2. LINQ to SQL follows SQL semantics, not C# semantics.

In SQL, SUM(no rows) returns null, not zero. However, the type inference for your query gives you decimal as the type parameter, instead of decimal?. The fix is to help type inference select the correct type, i.e.:

Employees.Where(e => e.EmployeeID == -999).Sum(e => (int?)e.EmployeeID)

Now the correct Sum() overload will be used.

这篇关于如何做的LINQ聚集时,有可能是一个空集?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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