Scott
Scott

Reputation: 4200

Sort List in C#

So I have this C# list:

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

Each JQGridMessage has a property called age. What's the quickest and most efficient way to sort this list by age (youngest first). Age is an int.

Thanks!

Upvotes: 6

Views: 4868

Answers (4)

Darren Young
Darren Young

Reputation: 11090

Can you use:

gridMessages = gridMessages.OrderBy(x => x.age).toList(); 

Upvotes: 0

Lee
Lee

Reputation: 144126

gridMessages.Sort((m1, m2) => m1.Age.CompareTo(m2.Age));

Upvotes: 3

JaredPar
JaredPar

Reputation: 754525

The List<T> class has a Sort method which can be used to in place sort the data. One overload takes a Comparison delegate that can be implemented via an anonymous function. For example

gridMessages.Sort((x, y) => x.Age.CompareTo(y.Age));

Upvotes: 9

Oded
Oded

Reputation: 498904

Use Linq:

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

This will return a new IEnumerable sorted by age.

Upvotes: 7

Related Questions