Created
May 8, 2015 08:10
-
-
Save derjabkin/a18416830252e2107c2b to your computer and use it in GitHub Desktop.
MaxBy extension
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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