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