Skip to content

Instantly share code, notes, and snippets.

@shoffing
Last active May 29, 2018 03:21
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save shoffing/9a4fb8fe6ffbe0afd2173faab22419fd to your computer and use it in GitHub Desktop.
Save shoffing/9a4fb8fe6ffbe0afd2173faab22419fd to your computer and use it in GitHub Desktop.
Adds the functional extension methods MinBy and MaxBy to IEnumerables.
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