Skip to content

Instantly share code, notes, and snippets.

@derjabkin
Created May 8, 2015 08:10
Show Gist options
  • Save derjabkin/a18416830252e2107c2b to your computer and use it in GitHub Desktop.
Save derjabkin/a18416830252e2107c2b to your computer and use it in GitHub Desktop.
MaxBy extension
public static TItem MaxBy<TItem, TValue>(this IEnumerable<TItem> items, Func<TItem, TValue> selector)
where TValue : IComparable
{
if (items == null)
throw new ArgumentNullException("items");
if (selector == null)
throw new ArgumentNullException("selector");
TItem maxItem = items.FirstOrDefault();
TValue maxValue = selector(maxItem);
foreach (var item in items)
{
var value = selector(item);
if (value.CompareTo(maxValue) > 0)
{
maxValue = value;
maxItem = item;
}
}
return maxItem;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment