MaxObject

public static T MaxObject<T, U>(this List<T> source, Func<T, U> selector)
    where U : IComparable<U>
{
    if (source == null) throw new ArgumentNullException("source");
    bool first = true;
    T maxObj = default(T);
    U maxKey = default(U);
    foreach (var item in source)
    {
        if (first)
        {
            maxObj = item;
            maxKey = selector(maxObj);
            first = false;
        }
        else
        {
            U currentKey = selector(item);
            if (currentKey.CompareTo(maxKey) > 0)
            {
                maxKey = currentKey;
                maxObj = item;
            }
        }
    }
    if (first) throw new InvalidOperationException("Sequence is empty.");
    return maxObj;
}
Example:
List<MyObject> myList = new List<MyObject>
    {
        new MyObject
            {
                ID = 0
            },
        new MyObject
            {
                ID = 1
            },
        new MyObject
            {
                ID = 2
            },

    };

MyObject objectIWant = myList.MaxObject(item => item.ID);

Description

Selects the object in a list with the maximum value on a particular property

Details

Double click on the code to select all.

 

;