Omer van Kloeten's .NET Zen

Programming is life, the rest is mere details

News

Omer van Kloeten's Facebook profile

Omer has been professionally developing applications over the past 8 years, both at the IDF’s IT corps and later at the Sela Technology Center, but has had the programming bug ever since he can remember himself.
As a senior developer at NuConomy, a leading web analytics and advertising startup, he leads a wide range of technologies for its flagship products.

Get Firefox


powered by Dapper 

.NET Resources

Articles :: CodeDom

Articles :: nGineer

Culture

Projects

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. :)

Comments

David Nelson said:

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 :)

# May 16, 2008 4:52 PM

Omer van Kloeten said:

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.

# May 16, 2008 7:05 PM

David Nelson said:

You're right. I would have sworn that such an overload existed, but now I can't find it. I must have written it myself at some point and then forgot that it wasn't in the framework :)

# May 20, 2008 5:52 PM
Leave a Comment

(required) 

(required) 

(optional)

(required)