Max Element in IEnumerable - CSharp System.Collections.Generic

CSharp examples for System.Collections.Generic:IEnumerable

Description

Max Element in IEnumerable

Demo Code


using System.Linq;
using System.Collections.Generic;
using System;/*from w  w  w .ja v  a 2  s . c o m*/

public class Main{
        public static T MaxElement<T>(this IEnumerable<T> enumerable, Func<T, int> selector)
    {
      var maxRank = int.MinValue;
      var maxElement = default(T);

      foreach (var element in enumerable)
      {
        var rank = selector(element);

        if (rank > maxRank)
        {
          maxRank = rank;
          maxElement = element;
        }
      }

      return maxElement;
    }
}

Related Tutorials