The general case, and not just for value types:
static class ExtensionsThatWillAppearOnEverything { public static T IfDefaultGiveMe<T>(this T value, T alternate) { if (value.Equals(default(T))) return alternate; return value; } } var result = query.FirstOrDefault().IfDefaultGiveMe(otherDefaultValue);
Again, this cannot really tell if there was something in your sequence, or if the first value was the default.
If you're interested, you can do something like
static class ExtensionsThatWillAppearOnIEnumerables { public static T FirstOr<T>(this IEnumerable<T> source, T alternate) { foreach(T t in source) return t; return alternate; } }
and use as
var result = query.FirstOr(otherDefaultValue);
although, as Mr. Steak points out, this can also be done with .DefaultIfEmpty(...).First() .
Rawling Oct 19 '12 at 10:34 2012-10-19 10:34
source share