FirstOrDefault for IEnumerable with non-empty content

I need to return the first item IEnumerable. And if IEnumerableempty, I return a special value.

The code for this might look like this:

return myEnumerable.FirstOrDefault() ?? mySpecialValue;

This is good and works fine as long as myEnumerableit contains no null elements.

In this case, the best I get is:

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

But here I have multiple listing myEnumerable!

How can i do this? I prefer to avoid any exceptions.

+4
source share
1 answer

You can use overload DefaultIfEmptyto specify your fallback value. Then you also do not need it FirstOrDefault, but you are safely using First:

return myEnumerable.DefaultIfEmpty(mySpecialValue).First();
+17
source

All Articles