Last element Based On function - CSharp System.Collections.Generic

CSharp examples for System.Collections.Generic:IList

Description

Last element Based On function

Demo Code


using System.Linq;
using System.Text;
using System.Globalization;
using System.ComponentModel;
using System.Collections.Generic;
using System.Collections;

public class Main{
        public static T LastBasedOn<T>(this IList<T> list, Func<T, IComparable> order) where T : class
        {/*from   w w w  .ja v  a 2s  .com*/
            if (list.Count == 0)
                return null;

            var itemLast = default(T);
            IComparable valueLast = null;
                
            foreach (var item in list)
            {
                var actual = order(item);

                if (valueLast == null || actual.CompareTo(valueLast) >= 0)
                {
                    valueLast = actual;
                    itemLast = item;
                }
            }

            return itemLast;
        }
}

Related Tutorials