Hit enter after type your search item

How to sort a list in C#?

As creating a List<T> in C#, its items may be in random order whether added by using the Add or Insert methods etc.

In this tutorial, I will show you how to sort a list in ascending or descending order by using the C# List Sort method and Linq with orderby keyword.

Sorting in ascending order by List Sort method

Using the Sort method of the List<T> class is simple. You may specify the List<T> name as follows:

myList.sort()

This will sort the myList items in ascending order. To demonstrate that, the code below created a list of int type. The list items are added in random order which is followed by using the the Sort method. See the List before and after using the Sort method:


The result:

c sharp sort-list

Sorting the list in descending order example

A trick for sorting the List<T> in descending order is using the reverse() method. The reverse() method is used to reverse the order of elements in the entire list (learn more here).

In that case, first, use the sort() method that will order the list in ascending order. After that, use the reverse() method for sorting that list in descending order.

The example below shows how:


The output:

c sharp sort list desc

This is how it worked. The Reverse() method is basically not for sorting the results in descending order. Instead, it simply reverses the order of items for the List<T>.

The use of Sort() method will bring the List<T> items in ascending order and so the reverse() will change the order that is descending.

Using LINQ orderby keyword for sorting a list

The other way of sorting a List<T> is using the Linq in C#. For that, you may use the OrderBy keyword as shown in the example below.

I created a List<T> of string elements and then used the LINQ OrderBy for sorting the elements in ascending order:


The result:

c sharp sort linq

Another way of using LINQ for ascending order sorting

The following example shows sorting the numeric list items in ascending order by using the Linq with orderby keyword in another way. Have a look:


The result:

1

3

4

5

9

Sorting in descending order example

Just by adding the descending keyword in with the orderby, you may get the list sorted in descending order. See the code and output below:


The result:

99

15

11

5

3

 

This div height required for enabling the sticky sidebar