Sorting a list of simple types like int, string, char etc. is straight forward. Just invoke the sort() method on the list instance and the data will be automatically sorting in asceding order.
1 2 3 4 |
List<int> numbers = new List<int> { 12, 33, 56, 45, 32, 5, 93, 1, 7 }; numbers.Sort(); |
If you want the data to be retrieved in descending order, use Reverse() methodvon the list instance.
1 2 3 |
numbers.Reverse(); |
Now it’s time to look at the first simple example of sorting a List.
Example 1:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 |
static void Main(string[] args) { List<int> numbers = new List<int> { 12, 33, 56, 45, 32, 5, 93, 1, 7 }; Console.WriteLine("Numbers before sorting "); foreach(int number in numbers) { Console.Write(number+ " "); } Console.WriteLine(); Console.WriteLine(); numbers.Sort(); Console.WriteLine("Numbers after sorting "); foreach (int number in numbers) { Console.Write(number + " "); } Console.WriteLine(); Console.WriteLine(); numbers.Reverse(); Console.WriteLine("Numbers in descending order "); foreach (int number in numbers) { Console.Write(number + " "); } Console.ReadKey(); } |
Output:
The code example here shows that I first sort the list and then revers the sorted list:
Example 2:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 |
static void Main(string[] args) { List<string> alphabets = new List<string> { "F","C","E","X","D","W" }; Console.WriteLine("Alphabets before sorting "); foreach(string alphabet in alphabets) { Console.Write(alphabet+ " "); } Console.WriteLine(); Console.WriteLine(); alphabets.Sort(); Console.WriteLine("Alphabets after sorting "); foreach (string alphabet in alphabets) { Console.Write(alphabet + " "); } Console.WriteLine(); Console.WriteLine(); alphabets.Reverse(); Console.WriteLine("Alphabets in descending order "); foreach (string alphabet in alphabets) { Console.Write(alphabet + " "); } Console.ReadKey(); } |
Output: