Skip to content

Instantly share code, notes, and snippets.

@juanplopes
Created May 4, 2011 15:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save juanplopes/955427 to your computer and use it in GitHub Desktop.
Save juanplopes/955427 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
{
var enumerator = source.GetEnumerator();
if (!enumerator.MoveNext()) return defaultValue;
TSource max = enumerator.Current;
while (enumerator.MoveNext())
{
var current = enumerator.Current;
if (current != null && current.CompareTo(max) > 0)
max = current;
}
return max;
}
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