Learnerslesson
   JAVA   
  SPRING  
  SPRINGBOOT  
 HIBERNATE 
  HADOOP  
   HIVE   
   ALGORITHMS   
   PYTHON   
   GO   
   KOTLIN   
   C#   
   RUBY   
   C++   




Sort() - Method


Sort() Method


The Sort() Method is used to sort a List in Ascending order.


Example :



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);  
        }
    }    
}


Output :



  Kriti
  Mohan
  Salim

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,

C_Sharp

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.

C_Sharp

And we get the below output.

Output :



  Kriti
  Mohan
  Salim

How to sort a List with numbers in Increasing Order?


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.


Example :



using System.Collections.Generic;
    
public class MyApplication
{
    public static void Main(string[] args)
    {
        var x = new List(){5, 3, 2, 4};
        x.Sort();
        
        foreach (var data in x)  
        {  
            System.Console.WriteLine(data);  
        }
    }    
}


Output :



  2
  3
  4
  5

So, in the above code we have created a List and initialised to the variable x.


var x = new List(){5, 3, 2, 4};

Below is how the values are positioned in the List,

C_Sharp

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.

C_Sharp

And we get the below output.

Output :



  2
  3
  4
  5

Next let us see, how to sort a List in Descending order.


How to sort a List with numbers in Descending Order?


Example :



using System.Collections.Generic;
    
public class MyApplication
{
    public static void Main(string[] args)
    {
        var x = new List(){5, 3, 2, 4};
        x.Sort();
        x.Reverse();
        foreach (var data in x)  
        {  
            System.Console.WriteLine(data);  
        }
    }    
}


Output :



  5
  4
  3
  2

So, in the above code we have created a List and initialised to the variable x.


var x = new List(){5, 3, 2, 4};

Below is how the values are positioned in the List,

C_Sharp

Then we have used the Sort() method to sort the List x in increasing order.


x.Sort();
C_Sharp


Then we have used the Reverse() method to reverse the List


x.Reverse();

And the List x gets sorted in decreasing order.

C_Sharp

And we get the below output.

Output :



  5
  4
  3
  2