FindMin() and FindMax()

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

Description

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

Details

Double click on the code to select all.