如何处理"InvalidOperationException Sequence contains no elements"

How to handle "InvalidOperationException Sequence contains no elements"

我有一个简单的函数 returns 一个月的平均销售额。但是,当新的一个月开始时,没有任何记录,我得到以下异常:

System.InvalidOperationException: 'Sequence contains no elements.'

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

}

处理此异常的最佳方法是什么?

最简单的可能就是用 try ... catch 和 return 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;
}