Home » c# » c# – Average of empty list throws InvalidOperationException: Sequence contains no elements

c# – Average of empty list throws InvalidOperationException: Sequence contains no elements

Posted by: admin February 21, 2020 Leave a comment

Questions:

The following code

double avg = item?.TechnicianTasks?.Average(x => x.Rating) ?? 0

throws

InvalidOperationException: Sequence contains no elements

the item.TechnicianTasks was supposed to be null, however I saw that it is an empty list, however why wouldn’t the average just be zero? I’m not understanding the exception.

How to&Answers:

Not much to it – it’s just how the code was written. Take a look at the docs and you’ll see –

Exceptions

ArgumentNullException – source is null.

InvalidOperationException – source contains no elements.

Makes sense though. You can’t get an average from zero items.