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 need FirstOrDefault
but you an use First
safely:
return myEnumerable.DefaultIfEmpty(mySpecialValue).First();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With