Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to handle "InvalidOperationException Sequence contains no elements"

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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;
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading