Home > Mobile >  How to handle "InvalidOperationException Sequence contains no elements"
How to handle "InvalidOperationException Sequence contains no elements"

Time:01-03

I have a simple function that returns average sales for a month. However, when a new month begins there are no records and I got the exception below:

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

}

What is the best way to handle this exception?

CodePudding user response:

The simplest would probably be just surrounding the block with a try ... catch and return 0 (or whatever other default value you want), if an execption is thrown

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
}

But as exceptions are expensive, you could check, if the collection you are trying to calculate the average of contains any elements

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;
}
  • Related