How to sort a list of 2D points using C#?
Sort a list of points in descending order according to X and th开发者_运维知识库en Y.
list.Sort((a,b)=>{
int result = a.X.CompareTo(b.X);
if(result==0) result = a.Y.CompareTo(b.Y);
return result;
});
An alternative way to Marc Gravell´s answer (which will sort the list itself) where you get an IEnumerable<T>
which can be made a list with .ToList()
is the LINQ syntax:
var ordered = from v in yourList
orderby v.X, v.Y
select v;
var orderedList = ordered.ToList();
But unless you don't want to actually sort the list itself or you only have, let's say an IEnumerable
, List.Sort
would be better.
List<Point> sortedList = MyList.Sort(
delegate(Point p1, Point p2)
{
int r = p1.x.CompareTo(p2.x);
if(r.Equals(0)) return p1.y.CompareTo(p2.y);
else return r;
}
);
If the commenters are indeed correct, and you're searching for a solution to a homework problem, I suspect the real assignment is teaching you how to sort integer values. So I'll just help get you started.
Hint: The Point
structure has two properties that you may find useful, X
and Y
, which return the coordinate values for those two axes, respectively.
There are many methods to sort a list.
For example, to sort your list from smallest (x, y) to biggest you can try this algorithm:
- Compare the first item in the list with the second
- If the second point is smaller than the first
(x1 > x2 || (x1 == x2 && y1 > y2))
then swap them around - Compare the second point with the third in the same way, and so on until you get to the end of the list
- Go back to the beginning of the list and run the comparisons again until the last but one element
- Repeat step 4 but stopping one element earlier each time until you've got no elements left to sort
This is an inefficient algorithm, but it will get the job done.
For better algorithms, have a look at http://www.sorting-algorithms.com/
精彩评论