Open In App

How to sort a list in C# | List.Sort() Method Set -2

Last Updated : 22 Sep, 2021
Comments
Improve
Suggest changes
Like Article
Like
Report
List<T>.Sort() Method is used to sort the elements or a portion of the elements in the List<T> using either the specified or default IComparer<T> implementation or a provided Comparison<T> delegate to compare list elements. There are total 4 methods in the overload list of this method as follows:
  1. Sort(IComparer<T>)
  2. Sort(Int32, Int32, IComparer)
  3. Sort()
  4. Sort(Comparison<T>)
Here, the first two methods are discussed in Set - 1. So, We will discuss the last two methods.
Sort() Method
This method is used to sort the elements in the entire List<T> using the default comparer.
Syntax: public void Sort (); Exception: This method will give InvalidOperationException if the default Comparer cannot find an implementation of the IComparable<T> generic interface or the IComparable interface for type T.
Example 1: csharp
// C# program to demonstrate the 
// use of List<T>.Sort() method
using System;
using System.Collections.Generic;

class GFG {

    // Main Method
    public static void Main()
    {

        // List initialize
        List<int> list1 = new List<int> {

            // list elements
            1, 5, 6, 2, 4, 3

        };

        Console.WriteLine("Original List");

        foreach(int g in list1)
        {

            // Display Original List
            Console.WriteLine(g);
        }

        Console.WriteLine("\nSorted List");

        // use of List<T>.Sort() method
        list1.Sort();

        foreach(int g in list1)
        {

            // Display sorted list
            Console.WriteLine(g);
        }
    }
}
Output:
Original List
1
5
6
2
4
3

Sorted List
1
2
3
4
5
6
Example 2: csharp
// C# program to demonstrate the 
// use of List<T>.Sort() method
using System;
using System.Collections.Generic;

class GFG {

    // Main Method
    public static void Main()
    {
        List<string> list1 = new List<string>();

        // list elements
        list1.Add("A");
        list1.Add("I");
        list1.Add("G");
        list1.Add("B");
        list1.Add("E");
        list1.Add("H");
        list1.Add("F");
        list1.Add("C");
        list1.Add("D");

        Console.WriteLine("Original List");

        // Display Original List
        Display(list1);

        Console.WriteLine("\nSorted List");

        // use of List.Sort() method
        list1.Sort();

        // Display sorted List
        Display(list1);
    }

    // Display function
    public static void Display(List<string> list)
    {
        foreach(string g in list)
        {
            Console.Write(g + " ");
        }
    }
}
Output:
Original List
A I G B E H F C D 
Sorted List
A B C D E F G H I
Example 3: csharp
// C# program to demonstrate the
// use of List<T>.Sort() method
using System;
using System.Collections.Generic;

public class GFG {

    // Main Method
    public static void Main()
    {
        // array elements
        String[] list = {"C++", "Java", "C",
                    "Python", "HTML", "CSS",
                    "Scala", "Ruby", "Perl"};

        var list1 = new List<String>();
  
        // "AddRange" method to add the
        // string array elements into the List
        list1.AddRange(list);
        

        Console.WriteLine("List in unsorted order: ");
        Display(list1);

        Console.WriteLine(Environment.NewLine);

        // using List.Sort() method
        list1.Sort();
        
        Console.WriteLine("List in sorted order: ");
        Display(list1);
    }

    // Display method
    static void Display(List<string> list)
    {
        foreach(string g in list)
        {
            Console.Write(g + "\t");
        }
    }
}
Output:
List in unsorted order: 
C++    Java    C    Python    HTML    CSS    Scala    Ruby    Perl    

List in sorted order: 
C    C++    CSS    HTML    Java    Perl    Python    Ruby    Scala
Sort(IComparer<T>) Method
This method is used to sort the elements in the entire List<T> using the specified comparer.
Syntax: public void Sort (Comparison<T> comparison); Parameter: comparison: It is the IComparer<T> implementation to use when comparing elements, or null to use the default comparer Default.
Exceptions:
  • ArgumentNullException: If the comparer is null, and the default comparer Default cannot find implementation of the IComparable<T> generic interface or the IComparable interface for type T.
  • ArgumentException: If the implementation of comparer caused an error during the sort. For example, comparer might not return 0 when comparing an item with itself.
Below programs illustrate the use of the above-discussed method: Example 1: csharp
// C# program to demonstrate the use of 
// List<T>.Sort(comparison <T>) method
using System;
using System.Collections.Generic;

class GFG {

    private static int Geek(string x,
                            string y)
    {
        if (x == null) {

            if (y == null) {

                // If x and y is null
                // then they are equal
                return 0;
            }

            else {

                // If x is null but y is not
                // null then y is greater.
                return -1;
            }
        }

        else {

            if (y == null) {

                return 1;
            }

            else {

                // If the strings are of equal length,
                // sort them with string comparison.
                return x.CompareTo(y);
            }
        }
    }
 
    // Main Method
    public static void Main()
    {
        List<string> list1 = new List<string>();

        // list elements
        list1.Add("AB");
        list1.Add("CD");
        list1.Add("GH");
        list1.Add("EF");
        list1.Add("IJ");
        list1.Add("KL");
        Console.WriteLine("Original List :");

        // displaying original list
        Display(list1);
       

        Console.WriteLine("\nSort with generic Comparison object :");

        // Sort(Comparison<t>) method
        //"Geek" is Comparison object
        list1.Sort(Geek);
        
        // displaying sorted list
        Display(list1);
       
    }

    // display function
    private static void Display(List<string> list)
    {
        foreach(string g in list)
        {
            Console.WriteLine(g);
        }
    }
}
Output:
Original List :
AB
CD
GH
EF
IJ
KL

Sort with generic Comparison object :
AB
CD
EF
GH
IJ
KL
Example 2: csharp
// C# program to demonstrate the use of
// List<T>.Sort(comparison <T>) method
using System;
using System.Collections.Generic;

class GFG {

    private static int Geek(int x, int y)
    {
        if (x == 0) {

            if (y == 0) {

                // If x and y is null
                // then they are equal
                return 0;
            }

            else {

                // If x is null but y is not 
                // null then y is greater.
                return -1;
            }
        }

        else {

            if (y == 0) {

                return 1;
            }

            else {

                // If the strings are of equal length,
                // sort them with string comparison.
                return x.CompareTo(y);
            }
        }
    }

    public static void Main()
    {
        List<int> list1 = new List<int>();

        // list elements
        list1.Add(2);
        list1.Add(5);
        list1.Add(6);
        list1.Add(4);
        list1.Add(1);
        list1.Add(3);

        Console.WriteLine("Original List :");

        // displaying original list
        Display(list1);
        
        Console.WriteLine("\nSort with generic "+
                          "Comparison object :");

         // Sort(Comparison<t>) method
        //"Geek" is Comparison object
        list1.Sort(Geek);
       
        // displaying sorted list
        Display(list1);     
    }

    // display function
    private static void Display(List<int> list)
    {
        foreach(int g in list)
        {
            Console.WriteLine(g);
        }
    }
}
Output:
Original List :
2
5
6
4
1
3

Sort with generic Comparison object :
1
2
3
4
5
6
Reference:

Next Article

Similar Reads