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!
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.
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; } } }
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.
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.
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));
Use Linq:
var sortedEnumerable = gridMessages.OrderBy(m => m.Age);
This will return a new IEnumerable sorted by age.
gridMessages.Sort((m1, m2) => m1.Age.CompareTo(m2.Age));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With