什么是Python的最小/最大的C#等效项

KFL*_*KFL 5 c# python

以下Python的最小/最大代码的C#等效项是什么:

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
Run Code Online (Sandbox Code Playgroud)

看来C#的Enumerable.Min非常接近。但是根据其MSDN文档,它总是返回最小化的VALUE(而不是原始对象)。我有什么想念的吗?

编辑


请注意 -我不倾向于首先通过排序来实现,因为排序(O(nlogn))在计算上比找到最小值(O(n))重。

另请注意 -词典也不是理想的方法。它不能处理键重复的情况-(1,“ cat”)和(1,“ tiger”)。

更重要的是,字典无法处理要处理的项目是复杂类的情况。例如,以年龄为关键字,找到一系列动物物体的最小值:

class Animal
{
  public string name;
  public int age;
}
Run Code Online (Sandbox Code Playgroud)

Cra*_*ney 3

BCL没有 MinBy 函数,但您自己编写一个很容易

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);
}
Run Code Online (Sandbox Code Playgroud)

您可以选择编写比我更复杂的 MinBy,以避免重新评估投影。无论如何,一旦有了 MinBy 函数,您就可以轻松解决问题:

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);
Run Code Online (Sandbox Code Playgroud)