What is faster in finding element with property of maximum value

前端 未结 4 732
没有蜡笔的小新
没有蜡笔的小新 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:58

    I will go with Max since it is specifically designed for that purpose. Sorting to find Max value seems to be too much.

    Also, I wouldn't use Where for finding the max, but Single - since what we need here is but a Single value.

    var maxValOfProperty = collection.Max(x => x.Property);
    var itemWithMaxPropValue = collection
                                .Single(x => x.Property == maxValueOfProperty);
    

    Or alternatively using First (if the collection contains duplicates of max value)

    var maxValOfProperty = collection.Max(x => x.Property);
    var itemWithMaxPropValue = collection
                                .First(x => x.Property == maxValueOfProperty);
    

    Or, using MoreLINQ (as suggested by Kathi), you could do it with MaxBy:

    var itemWithMaxPropValue = collection.MaxBy(x => x.Property);
    

    Check this post, on answer by Jon Skeet.

提交回复
热议问题