gpt4 book ai didi

c# - 如何在源集合为空时强制 LINQ Sum() 返回 0

转载 作者:IT王子 更新时间:2023-10-29 03:30:40 29 4
gpt4 key购买 nike

基本上,当我执行以下查询时,如果没有匹配的潜在客户,则以下查询会抛出异常。在那种情况下,我宁愿让总和等于 0 而不是抛出异常。这在查询本身中是否可能 - 我的意思是而不是存储查询并检查 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);

最佳答案

尝试将您的查询更改为:

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();

这样,您的查询将只选择 Amount 字段。如果集合为空,则返回一个值为 0 的元素,然后求和。

关于c# - 如何在源集合为空时强制 LINQ Sum() 返回 0,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17593371/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com