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?

1

2 Answers 2

3

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

list.Sort(delegate(Point p1, Point p2){
        return p1.X.CompareTo(p2.X);
});
Sign up to request clarification or add additional context in comments.

Comments

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;
}

1 Comment

I want to sort by a specific property, when it is a list of objects.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.