FirstOrDefault with a default value specified
///
/// Returns the first element of a sequence, or a default value if the
/// sequence contains no elements.
///
/// The type of the elements of
/// .
/// The to return
/// the first element of.
/// The default value to return if the sequence contains
/// no elements.
/// if is empty;
/// otherwise, the first element in .
public static T FirstOrDefault(this IEnumerable source, T @default)
{
if (source == null)
throw new ArgumentNullException("source");
using (var e = source.GetEnumerator())
{
if (!e.MoveNext())
return @default;
return e.Current;
}
}
///
/// Returns the first element of a sequence, or a default value if the sequence
/// contains no elements.
///
/// The type of the elements of
/// .
/// The to return
/// the first element of.
/// A function to test each element for a
/// condition.
/// The default value to return if the sequence contains
/// no elements.
/// if is empty
/// or if no element passes the test specified by ;
/// otherwise, the first element in that passes
/// the test specified by .
public static T FirstOrDefault(this IEnumerable source,
Func predicate, T @default)
{
if (source == null)
throw new ArgumentNullException("source");
if (predicate == null)
throw new ArgumentNullException("predicate");
using (var e = source.GetEnumerator())
{
while (true)
{
if (!e.MoveNext())
return @default;
if (predicate(e.Current))
return e.Current;
}
}
}