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:
Output:
Original List
1
5
6
2
4
3
Sorted List
1
2
3
4
5
6
Example 2:
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:
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:
Output:
Original List :
AB
CD
GH
EF
IJ
KL
Sort with generic Comparison object :
AB
CD
EF
GH
IJ
KL
Example 2: