Orace
Orace

Reputation: 8359

FirstOrDefault on IEnumerable with non-nullable contents

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.

Upvotes: 4

Views: 1094

Answers (1)

Tim Schmelter
Tim Schmelter

Reputation: 460028

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();

Upvotes: 17

Related Questions