C # sorting list

So, I have this C # list:

List<DatsWussup.Models.JQGridMessage> gridMessages = new List<DatsWussup.Models.JQGridMessage>(); 

Each JQGridMessage has a property called age . What is the fastest and most effective way to sort this list by age (younger first). Age is an int.

Thanks!

+6
sorting list c #
source share
4 answers

The List<T> class has a Sort method that can be used to sort data. One overload is accepted by the Comparison delegate, which can be implemented through an anonymous function. for example

 gridMessages.Sort((x, y) => x.Age.CompareTo(y.Age)); 
+9
source share

Use Linq:

 var sortedEnumerable = gridMessages.OrderBy(m => m.Age); 

This will return a new IEnumerable, sorted by age.

+6
source share
 gridMessages.Sort((m1, m2) => m1.Age.CompareTo(m2.Age)); 
+2
source share

Can you use:

 gridMessages = gridMessages.OrderBy(x => x.age).toList(); 
0
source share

All Articles