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

FindMin() and FindMax()

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

Source

static class Extensions {

    public static T FindMin<T, TValue>(this IEnumerable<T> list, Func<T, TValue> predicate)
                                                        where TValue : IComparable<TValue> {

        T result = list.FirstOrDefault();
        if (result != null) {
            var bestMin = predicate(result);
            foreach (var item in list.Skip(1)) {
                var v = predicate(item);
                if (v.CompareTo(bestMin) < 0) {
                    bestMin = v;
                    result = item;
                }
            }
        }
        return result;
    }

    public static T FindMax<T, TValue>(this IEnumerable<T> list, Func<T, TValue> predicate)
                                                            where TValue : IComparable<TValue> {
        T result = list.FirstOrDefault();
        if (result != null) {
            var bestMax = predicate(result);
            foreach (var item in list.Skip(1)) {
                var v = predicate(item);
                if (v.CompareTo(bestMax) > 0) {
                    bestMax = v;
                    result = item;
                }
            }
        }
        return result;
    }
}

Example

var l = new List<Employee>();
var r = new Random();
for (int i = 0; i < 1000000; i++) {
    l.Add(new Employee { Name = i.ToString(), Salary = r.Next(10000) });
}

Console.WriteLine(l.FindMin(emp => emp.Salary)?.Name);
Console.WriteLine(l.FindMax(emp => emp.Salary)?.Name);

Author: Fons Sonnemans

Submitted on: 7 okt. 2016

Language: C#

Type: System.Collections.Generic.IEnumerable<T>

Views: 5222