天天看點

C# linq 最大、最小對象的擴充

public static class LinqExtension
	{
		public static T MaxBy<T, TR>(this IEnumerable<T> en, Func<T, TR> evaluate) where TR : IComparable<TR>
		{
			return en.Select(t => new Tuple<T, TR>(t, evaluate(t)))
				.Aggregate((max, next) => next.Item2.CompareTo(max.Item2) > 0 ? next : max).Item1;
		}

		public static T MinBy<T, TR>(this IEnumerable<T> en, Func<T, TR> evaluate) where TR : IComparable<TR>
		{
			return en.Select(t => new Tuple<T, TR>(t, evaluate(t)))
				.Aggregate((max, next) => next.Item2.CompareTo(max.Item2) < 0 ? next : max).Item1;
		}

	}
           

  

轉載于:https://www.cnblogs.com/XuPengLB/p/8182400.html

c#