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 myEnumerable
contains 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.
You can use the overload of
DefaultIfEmpty
to specify your fallback value. Then you also don't needFirstOrDefault
but you an useFirst
safely: