Advertisement
KpoKec

MaxBy

Jul 29th, 2019
171
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 0.78 KB | None | 0 0
  1. public static TSource MaxBy<TSource, TProperty>(this IEnumerable<TSource> source,
  2.     Func<TSource, TProperty> selector)
  3. {
  4.     // check args        
  5.  
  6.     using (var iterator = source.GetEnumerator())
  7.     {
  8.         if (!iterator.MoveNext())            
  9.             throw new InvalidOperationException();
  10.  
  11.         var max = iterator.Current;
  12.         var maxValue = selector(max);
  13.         var comparer = Comparer<TProperty>.Default;
  14.  
  15.         while (iterator.MoveNext())
  16.         {
  17.             var current = iterator.Current;
  18.             var currentValue = selector(current);
  19.  
  20.             if (comparer.Compare(currentValue, maxValue) > 0)
  21.             {
  22.                 max = current;
  23.                 maxValue = currentValue;
  24.             }
  25.         }
  26.  
  27.         return max;
  28.     }
  29. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement