What is faster in finding element with property of maximum value

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

    Both solutions are not very efficient. First solution involves sorting whole collection. Second solution requires traversing collection two times. But you can find item with max property value in one go without sorting collection. There is MaxBy extension in MoreLINQ library. Or you can implement same functionality:

    public static TSource MaxBy(this IEnumerable source,
        Func selector)
    {
        // check args        
    
        using (var iterator = source.GetEnumerator())
        {
            if (!iterator.MoveNext())            
                throw new InvalidOperationException();
    
            var max = iterator.Current; 
            var maxValue = selector(max);
            var comparer = Comparer.Default;
    
            while (iterator.MoveNext())
            {
                var current = iterator.Current;
                var currentValue = selector(current);
    
                if (comparer.Compare(currentValue, maxValue) > 0)
                {
                    max = current;
                    maxValue = currentValue;
                }
            }
    
            return max;
        }
    }
    

    Usage is simple:

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

提交回复
热议问题