Sorting a list in C# can be done using the Sort()
class List< T > method.
We can sort the list in ascending order by simply calling the Sort()
method. By default, the Sort()
method sorts the list in ascending order.
Let’s sort lists of integers in ascending order:
using System;using System.Collections.Generic;class Sorting{static void Main(string[] args){List<int> numbers = new List<int>{ 4, 2, 1, 5, 3 };numbers.Sort(); // Sort the list in an ascending orderConsole.WriteLine("Sorted numbers:");for (int i = 0; i < numbers.Count; i++){int number = numbers[i];Console.WriteLine(number);}}}
After calling the Sort()
method, the numbers
list will be sorted in ascending order.
Line 8: Create a new integer type list and initialize it with five values.
Line 9:
Sort the elements of the numbers
list in ascending order.
Line 11:
Print the string "Sorted numbers:"
on the console.
Line 12:
This line of code initializes a loop that will iterate through all the elements of the numbers
list, from the first to the last.
Line 14:
Retrieves the ith element of the numbers
list and assigns its value to the number
variable.
Line 15: Print the value of number
on the console.
To sort a list in descending order, first, we have to convert the list in ascending order and then, by calling the Reverse()
method, sort the list in descending order.
Let’s sort lists of integers in a descending order:
using System;using System.Collections.Generic;class Sorting{static void Main(string[] args){List<int> numbers = new List<int>{ 4, 2, 1, 5, 3 };numbers.Sort(); // Sort the list in ascending ordernumbers.Reverse(); // Reverse the order of the elementsConsole.WriteLine("Sorted numbers:");for (int i = 0; i < numbers.Count; i++){int number = numbers[i];Console.WriteLine(number);}}}
After calling the Reverse()
method, the numbers
list will be sorted in descending order.
Line 8: Create a new integer type list and initialize it with five integer values.
Line 9:
Sort the elements of the numbers
list in ascending order.
Line 10: Reverse the order of elements in the numbers
list.
Line 11: Prints the string “Sorted numbers:” on the console.
Line 12:
This line of code initializes a loop that will iterate through all the elements of the numbers
list, from the first to the last.
Line 14:
Retrieves the ith element of the numbers
list and assigns its value to the number
variable.
Line 15: Print the value of number
on the console.
Free Resources