List .Sort() Method is used to sort the elements or a portion of the elements in the List using either the specified or default IComparer implementation or a provided Comparison delegate to compare list elements. There are total 4 methods in the overload list of this method as follows:
Here, we will discuss the first two methods.
Sort(IComparer ) Method
This method is used to sort the elements in the entire List using the specified comparer.
Syntax:
Here, the comparer is the IComparer 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 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.
Description
List Sort(Comparison ) sorts the elements in the entire List using the specified System.Comparison .
Syntax
Parameters
- comparison — The System.Comparison to use when comparing elements.
Example
The code above generates the following result.
I have created a class as follows:
I have created a list
it has few elements in it.
How do I sort this list using the Comparison comparison overload? The sorting must be done based on the num_of_words field.