Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort List in C#

Tags:

c#

list

sorting

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!

like image 256
Scott Avatar asked Apr 06 '11 21:04

Scott


People also ask

What is sort () and give example?

Sorting is the process of placing elements from a collection in some kind of order. For example, a list of words could be sorted alphabetically or by length. A list of cities could be sorted by population, by area, or by zip code.

What is sorting in array in C?

Each element is identified by using an "array index". Accessing array elements is easy by using the array index. The logic we use to sort the array elements in ascending order is as follows − for (i = 0; i < n; ++i){ for (j = i + 1; j < n; ++j){ if (num[i] > num[j]){ a = num[i]; num[i] = num[j]; num[j] = a; } } }

How do you sort a single linked list?

Below is a simple insertion sort algorithm for a linked list. 1) Create an empty sorted (or result) list 2) Traverse the given list, do following for every node. ......a) Insert current node in sorted way in sorted or result list. 3) Change head of given linked list to head of sorted (or result) list.

What is a sorted list in programming?

Master C and Embedded C Programming- Learn as you go A sorted list is a combination of an array and a hash table. It contains a list of items that can be accessed using a key or an index. If you access items using an index, it is an ArrayList, and if you access items using a key, it is a Hashtable.


3 Answers

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));
like image 193
JaredPar Avatar answered Oct 19 '22 05:10

JaredPar


Use Linq:

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

This will return a new IEnumerable sorted by age.

like image 26
Oded Avatar answered Oct 19 '22 05:10

Oded


gridMessages.Sort((m1, m2) => m1.Age.CompareTo(m2.Age));
like image 35
Lee Avatar answered Oct 19 '22 05:10

Lee