How to handle “InvalidOperationException Sequence contains no elements”

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

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top