我有一個簡單的函式,可以回傳一個月的平均銷售額。但是,當新的一個月開始時,沒有記錄,我得到以下例外:
System.InvalidOperationException: '序列不包含任何元素。'
public double GetTotalMonthlyAvgSales()
{
return _DbContext.Carts.Where(x => x.Created.Month == DateTime.UtcNow.Month && x.Created.Year == DateTime.UtcNow.Year).Select(x => x.TotalAmount).Average();
}
處理此例外的最佳方法是什么?
uj5u.com熱心網友回復:
最簡單的方法可能只是用 a 包圍塊try ... catch并回傳 0(或您想要的任何其他默認值),如果拋出 execption
public double GetTotalMonthlyAvgSales()
{
try {
return _DbContext.Carts.Where(x => x.Created.Month == DateTime.UtcNow.Month && x.Created.Year == DateTime.UtcNow.Year).Select(x => x.TotalAmount).Average();
} catch (InvalidOperationException ex) {
//if it's an InvalidOperationException return 0
return 0;
}
//any other exception will be rethrown
}
但是由于例外很昂貴,您可以檢查您嘗試計算平均值的集合是否包含任何元素
public double GetTotalMonthlyAvgSales()
{
var col = _DbContext.Carts.Where(x => x.Created.Month == DateTime.UtcNow.Month && x.Created.Year == DateTime.UtcNow.Year);
if (col.Any()) {
//if the collection has elements, you can calculate the average
return col.Select(x => x.TotalAmount).Average();
}
//if not, return 0
return 0;
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/402370.html
標籤:
