What's the C# equivalence of Python's min/max
c#, python
Solution
The BCL doesn't have a MinBy function, but it's easy to write one yourself.
public static T MinBy<T, C>(this IEnumerable<T> items, Func<T, C> projection) where C : IComparable<C> {
return items.Aggregate((acc, e) => projection(acc).CompareTo(projection(e)) <= 0 ? acc : e);
}
You may choose to write a more complex MinBy than me, in order to avoid re-evaluating the projection. In any case, once you have your MinBy function you can easily solve the problem:
var pairs = new[] {Tuple.Create(2,"dog"), Tuple.Create(1, "cat"), Tuple.Create(3, "dragon"), Tuple.Create(1, "tiger")};
var min_pair = pairs.MinBy(e => e.Item1);
Problem
What's C#'s equivalence of the following Python's min/max code: ``` pairs = [ (2,"dog"), (1, "cat"), (3, "dragon"), (1, "tiger") ] # Returns the PAIR (not the number) that minimizes on pair[0] min_pair = min(pairs, key=lambda pair:pair[0]) # this will return (1, 'cat'), NOT 1 ``` It seems that C#'s Enumerable.Min is very close. But according to its MSDN doc, it always returns the minimizing VALUE (not the original object). Am I missing anything? EDIT Please note - I'm not inclined to achieve this by sorting first, since sorting (O(nlogn)) is computationally heavier than finding the minimum (O(n)). Please also note - Dictionary is not a desired approach either. It cannot handle cases where there are duplicate keys - (1, "cat") and (1, "tiger"). More importantly, dictionary cannot handle cases where the items to be processed is a complex class. E.g., finding minimum over a list of animal objects, using age as the key: ``` class Animal { public string name; public int age; } ```