Сортировка List 2d точек - C#
Формулировка задачи:
Есть List из 2d точек, нужно отсортировать его так, чтобы возрастали х координаты при примерно одинаковых у координатах(с точностью 0.001). Затем у координаты увеличиваются и опять нужно отсортировать х координаты.
Применить Linq
не получилось как мне кажется из за того что у координаты слегка могут отличаться.
Такая функция(ниже) вроде как решает задачу.
Вопрос, можно ли здесь применить Linq?
points.OrderBy(p => p.y).ThenBy(p => p.x);
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ListSort
{
class Point
{
public double x, y;
public Point(double x, double y)
{
this.x = x; this.y = y;
}
}
class Program
{
static int ComparePoints(Point A, Point B)
{
int ires=0;
if (A.y < B.y)
ires = -1;
if (A.y > B.y)
ires = 1;
if (A.y == B.y)
{
if (A.x < B.x)
ires = -1;
if (A.x > B.x)
ires = 1;
}
return ires;
}
static void Main(string[] args)
{
List<Point> Points = new List<Point>();
Points.Add(new Point(0, 0));
Points.Add(new Point(23.6, 0));
Points.Add(new Point(47.2, 0));
Points.Add(new Point(70.8, 0));
Points.Add(new Point(94.4, 0));
Points.Add(new Point(118, 0));
Points.Add(new Point(141.6, 0));
Points.Add(new Point(35.4, 20.4382));
Points.Add(new Point(59, 20.4382));
Points.Add(new Point(82.6, 20.4382));
Points.Add(new Point(106.2, 20.4382));
Points.Add(new Point(129.8, 20.4382));
Points.Add(new Point(153.4, 20.4382));
Points.Add(new Point(70.8, 40.8764));
Points.Add(new Point(94.4, 40.8764));
Points.Add(new Point(118, 40.8764));
Points.Add(new Point(141.6, 40.8764));
Points.Add(new Point(106.2, 61.3146));
Points.Add(new Point(129.8, 61.3146));
Points.Add(new Point(47.2, 40.8764));
Points.Add(new Point(59, 61.3146));
Points.Add(new Point(70.8, 81.7528));
Points.Add(new Point(82.5999, 102.1911));
Points.Add(new Point(94.3999, 122.6293));
Points.Add(new Point(82.6, 61.3146));
Points.Add(new Point(94.4, 81.7528));
Points.Add(new Point(106.1999, 102.1911));
Points.Add(new Point(117.9999, 81.7529));
Points.Sort(ComparePoints);
int j = 1;
foreach (Point i in Points)
{
Console.Write("{0}\t{1}\t{2}", j, i.x.ToString(),i.y.ToString());
Console.WriteLine();
j++;
}
Console.ReadKey();
}
}
}Решение задачи: «Сортировка List 2d точек»
textual
Листинг программы
Points = Points.OrderBy(p => p.y, new MyComparer()).ThenBy(p => p.x).ToList();