Linq: FirstOrFallback

Sometimes you want to use FirstOrDefault, but the default value of T is a valid value that might get returned. If you used FirstOrDefault, you wouldn’t know whether the value that you got is a valid first or the default fallback. I use FirstOrFallback to explicitly specify which fallback value I want, rather than always use default(T):

public static T FirstOrFallback<T>(this IEnumerable<T> enumeration, T fallback)
{
// Check to see that enumeration is not null
if (enumeration == null)
throw new ArgumentNullException("enumeration");
IEnumerator<T> enumerator = enumeration.GetEnumerator();
enumerator.Reset();
if (enumerator.MoveNext())
return enumerator.Current;
return fallback;
}

On a side note: I realize most of the extension methods I post here are pretty obvious, but I love sharing time-saving code. :)

Advertisements

2 thoughts on “Linq: FirstOrFallback

  1. There is an overload of FirstOrDefault which takes a parameter to specify the default value to return if there are no items. Basically it does exactly what your method does, and its already in the framework :)

  2. Actually, no. The parameter you can pass to FirstOrDefault is a predicate that you can use to decide whether the item is ok to return, so you can use it like this:
    int n = integers.FirstOrDefault(i => i > 3);
    That will get you the first number in the list which is greater than 3, rather than the first number period.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s