Search code examples
c#listsortingpointgrasshopper

Sorting a List of points C#


I'm trying to sort a List (this Point3D is a Rhino library class). I want to have the points with the smallest X before, but I need to sort this points by the smallest Y if they have the same X. For example I have:

Point 1: X = 2; Y = 1
Point 2: X = 4; Y = 2
Point 3: X = 4; Y = 1
Point 4: X = 3; Y = 8
Point 5: X = 2; Y = 6
Point 6: X = 2; Y = 4

The order that I want to have is that:

Point 1: X = 2; Y = 1
Point 6: X = 2; Y = 4
Point 5: X = 2; Y = 6
Point 4: X = 3; Y = 8
Point 3: X = 4; Y = 1
Point 2: X = 4; Y = 2

I use this simple code:

myPointList.sort();

But I have an order that it's not the correct, because I have to remove some of this points, and if they have the order that I want, I erase the correct points but I remove the correct ones that I don't want to erase.

Can someone help me, please?

Thanks a lot!


Solution

  • Use Linq:

    Points.OrderBy(p => p.X).ThenBy(p => p.Y)