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.
You can use the overload of
DefaultIfEmptyto specify your fallback value. Then you also don't needFirstOrDefaultbut you an useFirstsafely: