How to sort a list in C# | List.Sort() Method Set -2
Last Updated :
22 Sep, 2021
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:
- Sort(IComparer<T>)
- Sort(Int32, Int32, IComparer)
- Sort()
- 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:
Similar Reads
Decorators in Python In Python, decorators are a powerful and flexible way to modify or extend the behavior of functions or methods, without changing their actual code. A decorator is essentially a function that takes another function as an argument and returns a new function with enhanced functionality. Decorators are
10 min read
AVL Tree Data Structure An AVL tree defined as a self-balancing Binary Search Tree (BST) where the difference between heights of left and right subtrees for any node cannot be more than one. The absolute difference between the heights of the left subtree and the right subtree for any node is known as the balance factor of
4 min read
Sliding Window Technique Sliding Window Technique is a method used to solve problems that involve subarray or substring or window. The main idea is to use the results of previous window to do computations for the next window. This technique is commonly used in algorithms like finding subarrays with a specific sum, finding t
13 min read
What is a Neural Network? Neural networks are machine learning models that mimic the complex functions of the human brain. These models consist of interconnected nodes or neurons that process data, learn patterns, and enable tasks such as pattern recognition and decision-making.In this article, we will explore the fundamenta
14 min read
Read JSON file using Python The full form of JSON is JavaScript Object Notation. It means that a script (executable) file which is made of text in a programming language, is used to store and transfer the data. Python supports JSON through a built-in package called JSON. To use this feature, we import the JSON package in Pytho
4 min read
ArrayList in Java Java ArrayList is a part of the collections framework and it is a class of java.util package. It provides us with dynamic-sized arrays in Java. The main advantage of ArrayList is that, unlike normal arrays, we don't need to mention the size when creating ArrayList. It automatically adjusts its capac
9 min read
Multithreading in Python This article covers the basics of multithreading in Python programming language. Just like multiprocessing , multithreading is a way of achieving multitasking. In multithreading, the concept of threads is used. Let us first understand the concept of thread in computer architecture. What is a Process
8 min read
Two Pointers Technique Two pointers is really an easy and effective technique that is typically used for Two Sum in Sorted Arrays, Closest Two Sum, Three Sum, Four Sum, Trapping Rain Water and many other popular interview questions. Given a sorted array arr (sorted in ascending order) and a target, find if there exists an
11 min read
Python Match Case Statement Introduced in Python 3.10, the match case statement offers a powerful mechanism for pattern matching in Python. It allows us to perform more expressive and readable conditional checks. Unlike traditional if-elif-else chains, which can become unwieldy with complex conditions, the match-case statement
7 min read
Regression in machine learning Regression in machine learning refers to a supervised learning technique where the goal is to predict a continuous numerical value based on one or more independent features. It finds relationships between variables so that predictions can be made. we have two types of variables present in regression
5 min read