[英]How can I set a zero-value instead of null in LINQ Select Sum
我試圖對我的EF Code First數據庫使用LINQ進行查詢,以檢索全年的銷售額,並返回一個新的DTO對象,該對象由月號和該月的總銷售額組成。
我的查詢工作正常,但是不包含銷售量的月份返回null而不是“ 0”,這在我的View中產生了問題。
我嘗試了空合並??
但是得到一個編譯錯誤,該錯誤對於decimal
無效。 我也嘗試了DefaultIfEmpty
但這似乎無法與.Sum方法一起使用。
有什么建議么?
模型:
public class YearlySalesDto
{
public string Month { get; set; }
public decimal TotalSales { get; set; }
}
查詢:
[AllowAnonymous]
public IEnumerable<YearlySalesDto> Index()
{
var result = from r in db.Orders
group r by r.OrderDate.Month into g
select new YearlySalesDto { Month = g.Key.ToString() ?? "", TotalSales = g.Sum(p => p.OrderItems.Select(x => x.Quantity * x.UnitPrice).Sum()) };
if (result == null)
{
throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.NotFound));
}
return result;
}
此查詢的結果,因為我只有第3個月和第4個月的銷售記錄在數據庫中。
[
{
"Month": "3",
"TotalSales": 158
},
{
"Month": "4",
"TotalSales": 373
}
]
您的選擇與該問題無關,您可以擺脫它並仍然看到問題, GroupBy
不會返回g.Count == 0
值,您需要做的是添加沒有行的月份的占位符條目在db.Orders
中db.Orders
為0,並將其與您的結果合並。
var result = from r in db.Orders
group r by r.OrderDate.Month
into g
select new YearlySalesDto {
Month = g.Key.ToString(), // The ?? "" is unnecessary.
TotalSales = g.Sum(p => p.OrderItems.Select(x => x.Quantity * x.UnitPrice).Sum())
};
var fixedResult = result.AsEnumerable()
.Union(Enumerable.Range(1,12)
.Select(x=>new YearlySalesDto { Month = x.ToString(), TotalSales = 0 })
, new MonthComparer());
//Elsewhere
class MonthComparer : IEqualityComparer<YearlySalesDto>
{
public bool Equals(YearlySalesDto x, YearlySalesDto y)
{
return x.Month == y.Month;
}
public int GetHashCode(YearlySalesDto x)
{
return x.Month.GetHashCode();
}
}
@Scott在上面的注釋中解釋了您收到的編譯錯誤。
至於幾個月的零值,則數據庫中沒有的剩余部分將結果與幾個月的集合結合起來,如果為null
則為0
:
var result = from m in Enumerable.Range(1,12)
join g in db.Orders.GroupBy(r => r.OrderDate.Month) on m equals g.Key into joint
from g in joint.DefaultIfEmpty()
select new YearlySalesDto {
Month = m.ToString(),
TotalSales = g == null ? 0 : g.Sum(p => p.OrderItems.SelectMany(x => x.Quantity * x.UnitPrice))
};
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.