Friday, February 16, 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

plot explanation - Why did Peaches' mom hang on the tree? - Movies & TV

In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...