0

In .NET 4.0 you can simply use LINQ to quickly sort a list by a specific property:

  List<Point> list = ...;    
  sorted = list.OrderBy(p => p.X).ToList(); // sort list of points by X

Can you do something similar when you cannot use .NET 4.0 LINQ syntax?

Is there a one-liner sort syntax?

Robin Rodricks
  • 110,798
  • 141
  • 398
  • 607

2 Answers2

3

Check Sort method, that takes Comparison<T>. Avaliable from .NET 2.0

var list = new List<Point>{ /* populate list */ };

list.Sort(Comparison);


public int Comparison (Point a, Point b)
{
    //do logic comparison with a and b
    return -1;
}
Ilya Ivanov
  • 23,148
  • 4
  • 64
  • 90
3

You need to use a delegate, almost a one-liner :)

list.Sort(delegate(Point p1, Point p2){
        return p1.X.CompareTo(p2.X);
});
Robin Rodricks
  • 110,798
  • 141
  • 398
  • 607