Skip to content

Instantly share code, notes, and snippets.

@evillegas92
Created April 22, 2019 16:38
Show Gist options
  • Save evillegas92/d0a89cdbc5dc89e7fb0bff5e927b765d to your computer and use it in GitHub Desktop.
Save evillegas92/d0a89cdbc5dc89e7fb0bff5e927b765d to your computer and use it in GitHub Desktop.
public static class EnumerableExtensions
{
public static T WithMinimum<T, TKey>(this IEnumerable<T> sequence, Func<T, TKey> criterion)
where T: class
where TKey : IComparable<TKey> =>
sequence.Select(obj => Tuple.Create(obj, criterion(obJ)))
.Aggregate((Tuple<T, Tkey>)null,
(best, cur) => best == null || cur.Item2.CompareTo(best.Item2) < 0 ? cur : best)
.Item1;
}
@evillegas92
Copy link
Author

Extension method to find the element in the sequence with the minimum value for a given property.

@evillegas92
Copy link
Author

Usage:
private static IPainter FindCheapestPainter(double sqMeters, IEnumerable<IPainter> painters) { return painters .Where(painter => painter.IsAvailable) .WithMinimum(painter => painter.EstimateCompensation(sqMeters)); }

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment