Time for action – sorting 2D points by their co-ordinates

Let's say we have an array of points in 2D and we want to sort them as per their X co-ordinates. Here is how to do it:

  1. Copy the following code snippet as a query to LINQPad:
    System.Drawing.PointF[] points = 
    {
      new System.Drawing.PointF(0, -1),
      new System.Drawing.PointF(-1, 1),
      new System.Drawing.PointF(3, 3)
    };
    
    var sortedPoints = points.Select(c=>new {X = c.X, Y = c.Y}).OrderBy(c => c.X).ToList();
    
    sortedPoints.Dump("Sorted Points");
  2. Run the query. You should see the following output:
    Time for action – sorting 2D points by their co-ordinates

What just happened?

We have a List of points in 2D and we wanted to sort them by their X co-ordinates. We created ...

Get .NET 4.0 Generics now with the O’Reilly learning platform.

O’Reilly members experience live online training, plus books, videos, and digital content from nearly 200 publishers.