我有一个点列表(List):
- 7,43
- 7,42
- 6,42
- 5,42
- 6,43
- 5,43
我想使用LINQ表达式来获取最靠近0,0的点。例如-对于这个列表,我期望得到的值是5,42。
如何使用LINQ查找距离0,0最近的点?
var closestToOrigin = points
.Select(p => new { Point = p, Distance2 = p.X * p.X + p.Y * p.Y })
.Aggregate((p1, p2) => p1.Distance2 < p2.Distance2 ? p1 : p2)
.Point;
试试这个:
List<Point> points = new List<Point>();
// populate list
var p = points.OrderBy(p => p.X * p.X + p.Y * p.Y).First();
var p = points.Aggregate(
(minPoint, next) =>
(minPoint.X * minPoint.X + minPoint.Y * minPoint.Y)
< (next.X * next.X + next.Y * next.Y) ? minPoint : next);
IOrderedEnumerable
的First
重载,那就不会有问题了!) - RawlingRawling的解决方案确实更简短,但这里有一个替代方案
// project every element to get a map between it and the square of the distance
var map = pointsList
.Select(p => new { Point = p, Distance = p.x * p.x + p.y * p.y });
var closestPoint = map // get the list of points with the min distance
.Where(m => m.Distance == map.Min(t => t.Distance))
.First() // get the first item in that list (guaranteed to exist)
.Point; // take the point
First
并执行Select(p => p.Point)
以获取点(而不是映射)即可。log(n)
真是致命的。我已经更新了我的答案。 - vladvar result = points.MinBy( p => p.X*p.X + p.Y*p.Y );
Jon Skeet提供了MinBy和MaxBy的良好实现。
他在这里讲述了它:如何使用LINQ选择具有最小或最大属性值的对象
从那里的链接已经过时,但最新版本在这里:
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);
}
}
}
x, y
到0,0
的距离是sqrt(x^2 + y^2)
吗? - vladpoints = points.OrderBy(p => p.X).ThenBy(p => p.Y).ToList()
。 - Mathew Thompson