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, we will discuss the first two methods.
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 (System.Collections.Generic.IComparer<T> comparer);
Here, the comparer is the IComparer<T> implementation to use when comparing elements, or null to use the default comparer Default.
Exceptions:
- InvalidOperationException: If the comparer is null, and the default comparer Default cannot find the 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.
Example 1:
Output:
Original List
1
5
6
2
4
3
Sort with a comparer:
1
2
3
4
5
6
Example 2:
Output:
Original List
A
I
G
B
E
H
F
C
J
Sort with a comparer:
A
B
C
E
F
G
H
I
J
BinarySearch and Insert D
A
B
C
D
E
F
G
H
I
J
List<T>.Sort(Int32, Int32, IComparer<T>) Method
This method is used to sort the elements in a range of elements in List<T> using the specified comparer.
Syntax:
public void Sort(int index, int len, IComparer<T> comparer)
Parameters:
index : It is the zero-based starting index of the range in which sort will happen.
len : It is the length of the range.
comparer : When comparing elements then use the IComparer implementation or null to use the default comparer Default.
Exceptions:
- ArgumentOutOfRangeException : If indexor len is less than 0.
- ArgumentException : If index and count do not specify a valid range in the List.
- InvalidOperationException : If comparer is null.
Example: