作为一种替代方法,您可以考虑在标准库中添加 IEnumerable.MinBy() 和 IEnumerable.MaxBy() 的实现。
如果你有可用的,代码就变得简单了:
var result = points.MinBy( p => p.X*p.X + p.Y*p.Y );
Jon Skeet 提供了 MinBy 和 MaxBy 的良好实现。
他在这里谈论它:How to use LINQ to select object with minimum or maximum property value
但是那里的链接已经过时了;最新版本在这里:
http://code.google.com/p/morelinq/source/browse/MoreLinq/MinBy.cs
http://code.google.com/p/morelinq/source/browse/MoreLinq/MaxBy.cs
这是一个完整的示例。显然,这是一把大锤,但我认为这些方法足够有用,可以包含在您的标准库中:
using System;
using System.Collections.Generic;
using System.Drawing;
namespace Demo
{
public static class EnumerableExt
{
public static TSource MinBy<TSource, TKey>(this IEnumerable<TSource> source, Func<TSource, TKey> selector, IComparer<TKey> comparer)
{
using (IEnumerator<TSource> sourceIterator = source.GetEnumerator())
{
if (!sourceIterator.MoveNext())
{
throw new InvalidOperationException("Sequence was empty");
}
TSource min = sourceIterator.Current;
TKey minKey = selector(min);
while (sourceIterator.MoveNext())
{
TSource candidate = sourceIterator.Current;
TKey candidateProjected = selector(candidate);
if (comparer.Compare(candidateProjected, minKey) < 0)
{
min = candidate;
minKey = candidateProjected;
}
}
return min;
}
}
public static TSource MinBy<TSource, TKey>(this IEnumerable<TSource> source, Func<TSource, TKey> selector)
{
return source.MinBy(selector, Comparer<TKey>.Default);
}
}
public static class Program
{
static void Main(string[] args)
{
List<Point> points = new List<Point>
{
new Point(7, 43),
new Point(7, 42),
new Point(6, 42),
new Point(5, 42),
new Point(6, 43),
new Point(5, 43)
};
var result = points.MinBy( p => p.X*p.X + p.Y*p.Y );
Console.WriteLine(result);
}
}
}