What is faster in finding element with property of maximum value

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

    Sorting is N * log (N) while Max has N only time complexity, so Max is faster. What you're looking for is ArgMax function which Linq doesn't provide, so I suggest implementing it, e.g:

      public static class EnumerableExtensions {
        public static T ArgMax(this IEnumerable source, 
                                     Func map, 
                                     IComparer comparer = null) {
          if (Object.ReferenceEquals(null, source))
            throw new ArgumentNullException("source");
          else if (Object.ReferenceEquals(null, map))
            throw new ArgumentNullException("map");
    
          T result = default(T);
          K maxKey = default(K);
          Boolean first = true;
    
          if (null == comparer)
            comparer = Comparer.Default;
    
          foreach (var item in source) {
            K key = map(item);
    
            if (first || comparer.Compare(key, maxKey) > 0) {
              first = false;
              maxKey = key;
              result = item;
            }
          }
    
          if (!first)
            return result;
          else
            throw new ArgumentException("Can't compute ArgMax on empty sequence.", "source");
        }
      }
    

    So you can put it simply

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

提交回复
热议问题