Shortest code to calculate list min/max in .NET

后端 未结 4 1988
旧时难觅i
旧时难觅i 2020-12-10 04:45

I\'d like something like

int minIndex = list.FindMin(delegate (MyClass a, MyClass b) {returns a.CompareTo(b);});

Is there a builtin way to

4条回答
  •  情书的邮戳
    2020-12-10 05:12

    You note that "I'm still in 2" - you might, then, want to look at LINQBridge. This is actually aimed at C# 3.0 and .NET 2.0, but you should be able to use it with C# 2.0 and .NET 2.0 - just you'll have to use the long-hand:

    MyClass min = Enumerable.Min(list),
            max = Enumerable.Max(list);
    

    Of course, it will be easier if you can switch to C# 3.0 (still targetting .NET 2.0).

    And if LINQBridge isn't an option, you can implement it yourself:

    static void Main()
    {
        int[] data = { 3, 5, 1, 5, 5 };
        int min = Min(data);
    }
    static T Min(IEnumerable values)
    {
        return Min(values, Comparer.Default);
    }
    static T Min(IEnumerable values, IComparer comparer)
    {
        bool first = true;
        T result = default(T);
        foreach(T value in values) {
            if(first)
            {
                result = value;
                first = false;
            }
            else
            {
                if(comparer.Compare(result, value) > 0) 
                {
                    result = value;
                }
            }
        }
        return result;
    }
    

提交回复
热议问题