Last active
May 29, 2018 03:21
-
-
Save shoffing/9a4fb8fe6ffbe0afd2173faab22419fd to your computer and use it in GitHub Desktop.
Adds the functional extension methods MinBy and MaxBy to IEnumerables.
This file contains hidden or 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
using System; | |
namespace System.Collections.Generic | |
{ | |
public static class MinMaxBy | |
{ | |
public static T MinBy<T>(this IEnumerable<T> list, Func<T, IComparable> selector) | |
{ | |
IComparable lowest = null; | |
T result = default(T); | |
foreach (T elem in list) | |
{ | |
var currElemVal = selector(elem); | |
if (lowest == null || currElemVal.CompareTo(lowest) < 0) | |
{ | |
lowest = currElemVal; | |
result = elem; | |
} | |
} | |
return result; | |
} | |
public static T MaxBy<T>(this IEnumerable<T> list, Func<T, IComparable> selector) | |
{ | |
IComparable highest = null; | |
T result = default(T); | |
foreach (T elem in list) | |
{ | |
var currElemVal = selector(elem); | |
if (highest == null || currElemVal.CompareTo(highest) > 0) | |
{ | |
highest = currElemVal; | |
result = elem; | |
} | |
} | |
return result; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment