如何强制LINQ总和()返回0,而源集合为空 [英] How to force LINQ Sum() to return 0 while source collection is empty

查看:92
本文介绍了如何强制LINQ总和()返回0,而源集合为空的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

基本上,当我做下面的查询,如果没有线索相匹配下面的查询会抛出异常。在这种情况下,我想preFER有总和相等0而不是抛出的异常。
这会不会有可能在查询本身 - 我的意思,而不是存储查询和检查 query.Any()

 双重收益= db.Leads.Where(L => l.Date.Day == date.Day
                &功放;&安培; l.Date.Month == date.Month
                &功放;&安培; l.Date.Year == date.Year
                &功放;&安培; l.Property.Type == ProtectedPropertyType.Password
                &功放;&安培; l.Property.PropertyId ==物业ID).SUM(L => l.Amount);


解决方案

试着改变你的查询这样的:

  db.Leads.Where(L => l.Date.Day == date.Day
            &功放;&安培; l.Date.Month == date.Month
            &功放;&安培; l.Date.Year == date.Year
            &功放;&安培; l.Property.Type == ProtectedPropertyType.Password
            &功放;&安培; l.Property.PropertyId ==物业ID)
         。选择(L => l.Amount)
         .DefaultIfEmpty(0)
         。和();

这样,你的查询只会选择金额字段。如果集合是空的,它会返回一个元素与值 0 ,然后总和将被应用。

Basically when I do the following query, if no leads were matched the following query throws an exception. In that case I'd prefer to have the sum equalize 0 rather than an exception being thrown. Would this be possible in the query itself - I mean rather than storing the query and checking query.Any() ?

double earnings = db.Leads.Where(l => l.Date.Day == date.Day
                && l.Date.Month == date.Month
                && l.Date.Year == date.Year
                && l.Property.Type == ProtectedPropertyType.Password
                && l.Property.PropertyId == PropertyId).Sum(l => l.Amount);

解决方案

Try changing your query to this:

db.Leads.Where(l => l.Date.Day == date.Day
            && l.Date.Month == date.Month
            && l.Date.Year == date.Year
            && l.Property.Type == ProtectedPropertyType.Password
            && l.Property.PropertyId == PropertyId)
         .Select(l => l.Amount)
         .DefaultIfEmpty(0)
         .Sum();

This way, your query will only select the Amount field. If the collection is empty, it will return one element with the value of 0 and then the sum will be applied.

这篇关于如何强制LINQ总和()返回0,而源集合为空的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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