본문 바로가기
카테고리 없음

c# find nearest element in list / sort by distance

by 아리꽃천사 2017. 12. 27.

public void TestMinDistance()

{

List<Point> list = new List<Point>()

{

new Point(1, 1),

new Point(2, 1),

new Point(2, 0),

};


Point pivot = new Point(3, 1);


Func<Point, Point, double> DistanceTo = (point1, point2) =>

{

var a = (double)(point2.X - point1.X);

var b = (double)(point2.Y - point1.Y);


return Math.Sqrt(a * a + b * b);

};


Point nearest = list

.Aggregate((x, y) => DistanceTo(x, pivot) < DistanceTo(y, pivot) ? x : y);


Debug.WriteLine(nearest);


// sort by distance

List<Point> sortedList = list

.OrderBy(x => DistanceTo(x, pivot))

.ToList();


sortedList.ForEach(p => Debug.WriteLine(p));

}



https://stackoverflow.com/a/5954005

http://www.vcskicks.com/code-snippet/distance-formula.php

댓글