The Sort() Method is used to sort a List in Ascending order.
using System.Collections.Generic; public class MyApplication { public static void Main(string[] args) { var x = new List<string>(){"Mohan", "Kriti", "Salim"}; x.Sort(); foreach (var data in x) { System.Console.WriteLine(data); } } }
So, in the above code we have created a List and initialised to the variable x.
var x = new List<string>(){"Mohan", "Kriti", "Salim"};
Below is how the values are positioned in the List,
Then we have used the Sort() method to sort the List x in ascending order.
x.Sort();
And the List x gets sorted with Kriti as the first value, Mohan second and Salim as the third.
And we get the below output.
Even here the Sort() Method is used to sort a List with numbers in Increasing/Deceasing Order.
At first let us see an example to sort a List with numbers in Increasing order.
using System.Collections.Generic; public class MyApplication { public static void Main(string[] args) { var x = new List<int>(){5, 3, 2, 4}; x.Sort(); foreach (var data in x) { System.Console.WriteLine(data); } } }
So, in the above code we have created a List and initialised to the variable x.
var x = new List<int>(){5, 3, 2, 4};
Below is how the values are positioned in the List,
Then we have used the Sort() method to sort the List x in increasing order.
x.Sort();
And the numbers in the List x gets sorted.
And we get the below output.
Next, let us see, how to sort a List in Descending order.
using System.Collections.Generic; public class MyApplication { public static void Main(string[] args) { var x = new List<int>(){5, 3, 2, 4}; x.Sort(); x.Reverse(); foreach (var data in x) { System.Console.WriteLine(data); } } }
So, in the above code we have created a List and initialised to the variable x.
var x = new List<int>(){5, 3, 2, 4};
Below is how the values are positioned in the List,
Then we have used the Sort() method to sort the List x in increasing order.
x.Sort();
Then we have used the Reverse() method to reverse the List
x.Reverse();
And the List x gets sorted in decreasing order.
And we get the below output.