MinBy, MaxBy を作る
using System; using System.Collections.Generic; using System.Linq; public static class Ext { public static T MinBy<T, U>(this IEnumerable<T> xs, Func<T, U> key) where U : IComparable<U> { return xs.Aggregate((a, b) => key(a).CompareTo(key(b)) < 0 ? a : b); } public static T MaxBy<T, U>(this IEnumerable<T> xs, Func<T, U> key) where U : IComparable<U> { return xs.Aggregate((a, b) => key(a).CompareTo(key(b)) > 0 ? a : b); } } class Program { static void Main() { var xs = new List<int[]> { new[] { 1, 2 }, new[] { 20, 50 }, new[] { 30, 22 }, new[] { 50, -100 }, }; // 1 番目の要素が最小 var a = xs.MinBy(e => e[1]); Console.WriteLine(string.Join(" ", a)); // 50 -100 // 1 番目の要素が最大 var b = xs.MaxBy(e => e[1]); Console.WriteLine(string.Join(" ", b)); // 20 50 // 要素数が 1 の場合 var c = new[] { 123 }.MinBy(e => e); Console.WriteLine(c); // 123 // 要素数が 0 の場合 // var d = new int[0].MinBy(e => e); // Console.WriteLine(d); // System.InvalidOperationException: Sequence contains no elements } }
実行結果です。
50 -100 20 50 123