ExtensionMethod.NET Home of 880 C#, Visual Basic, F# and Javascript extension methods

MaxObject

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

Source

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);

Author: James Pattison

Submitted on: 6 aug. 2013

Language: C#

Type: List Extensions

Views: 4559