What is faster in finding element with property of maximum value

前端 未结 4 773
没有蜡笔的小新
没有蜡笔的小新 2021-01-18 02:31

Commonly, to find element with property of max value I do like this

var itemWithMaxPropValue = collection.OrderByDescending(x => x.Property).First();
         


        
4条回答
  •  青春惊慌失措
    2021-01-18 02:46

    The maximum element under some specified function can also be found by means of the following two functions.

    static class Tools
    {
        public static T ArgMax(T t1, T t2, Func f)
        where R : IComparable
        {
            return f(t1).CompareTo(f(t2)) > 0 ? t1 : t2;
        }
    
        public static T ArgMax(this IEnumerable Seq, Func f)
        where R : IComparable
        {
            return Seq.Aggregate((t1, t2) => ArgMax(t1, t2, f));
        }
    }
    

    The solution above works as follows; the first overload of ArgMax takes a comparator as an argument which maps both instances of T to a type which implements comparability; a maximum of these is returned. The second overload takes a sequence as an argument and simply aggregates the first function. This is the most generic, framework-reusing and structurally sound formulation for maximum search I am aware of; searching the minimum can be implemented in the same way by changing the comparison in the first function.

提交回复
热议问题