Using Entity Framework Core I have the following query:
var avgDuration = await projects.AverageAsync(x => x.Duration);
When the enumeration projects
is empty I get the following error:
InvalidOperationException: Sequence contains no elements.
Is there a way to AverageAsync
to not throw exception when enumeration as not elements.
Should not just return null?
Is there a way to
AverageAsync
to not throw exception when enumeration as not elements.Should not just return null?
Average
and AverageAsync
(as well as Min
, Max
) will return null
on empty set when the value type is nullable. If it is not, just promote it to the corresponding nullable type using C# cast operator.
For instance, if in your sample the type of x.Duration
is int
, then use int?
cast:
var avgDuration = await projects.AverageAsync(x => (int?)x.Duration);
And if you want to get 0 (zero) when the source set is empty, then simply apply ?? 0
to the result.