Skip to content

Instantly share code, notes, and snippets.

@elvisgs
Forked from juanplopes/gist:955427
Created May 5, 2011 03:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save elvisgs/956482 to your computer and use it in GitHub Desktop.
Save elvisgs/956482 to your computer and use it in GitHub Desktop.
MaxOrDefault sem catch
public static TSource MaxOrDefault<TSource>(this IEnumerable<TSource> source)
where TSource : IComparable
{
return source.MaxOrDefault(default(TSource));
}
public static TSource MaxOrDefault<TSource>(this IEnumerable<TSource> source, TSource defaultValue)
where TSource : IComparable
{
return source.Aggregate(defaultValue, (a, b) => a != null && a.CompareTo(b) > 0 ? a : b);
}
public static TSource MaxOrDefault<TSource>(this IEnumerable<TSource?> source)
where TSource : struct, IComparable
{
return source.MaxOrDefault(default(TSource));
}
public static TSource MaxOrDefault<TSource>(this IEnumerable<TSource?> source, TSource defaultValue)
where TSource : struct, IComparable
{
return source.Where(x => x != null).Select(x => x ?? default(TSource)).MaxOrDefault(defaultValue);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment