Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

FirstOrDefault on IEnumerable with non-nullable contents

Tags:

c#

ienumerable

I need to return the first element of an IEnumerable. And if the IEnumerable is empty I return a special value.

The code for this can look like this :

return myEnumerable.FirstOrDefault() ?? mySpecialValue;

This is nice and work fine until myEnumerablecontains nullable stuffs.

In this case, the best I get is :

return myEnumerable.Any() ? myEnumerable.First() : mySpecialValue;

But here I have multiple enumeration of myEnumerable !

How can I do it ? I prefer to avoid to have to catch any exception.

like image 625
Orace Avatar asked Dec 03 '22 16:12

Orace


1 Answers

You can use the overload of DefaultIfEmpty to specify your fallback value. Then you also don't need FirstOrDefault but you an use First safely:

return myEnumerable.DefaultIfEmpty(mySpecialValue).First();
like image 93
Tim Schmelter Avatar answered Jan 14 '23 18:01

Tim Schmelter