Friday, 16 February 2018

c# - How to sort a list by a specific property in .NET 2.0?




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




  List 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?


Answer



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




list.Sort(delegate(Point p1, Point p2){
return p1.X.CompareTo(p2.X);
});

No comments:

Post a Comment

casting - Why wasn't Tobey Maguire in The Amazing Spider-Man? - Movies & TV

In the Spider-Man franchise, Tobey Maguire is an outstanding performer as a Spider-Man and also reprised his role in the sequels Spider-Man...