TheDeveloperBlog.com

Home | Contact Us

C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML

C# IComparable Example With CompareTo

This C# article demonstrates the IComparable generic interface. It helps with custom sorting algorithms.

IComparable allows custom sorting of objects when implemented. When a class implements this interface, we must add the public method CompareTo(T). We implement custom sorting for a class with IComparable.

Interface

Example. Please look at the Employee class. This class implements IComparable<Employee>, which means an Employee instance can be compared with other Employee instances. The Employee class has two instance properties: Salary and Name.

Also: The Employee class provides the CompareTo(Employee) method and the ToString method.

C# program that implements IComparable interface

using System;
using System.Collections.Generic;

class Employee : IComparable<Employee>
{
    public int Salary { get; set; }
    public string Name { get; set; }

    public int CompareTo(Employee other)
    {
	// Alphabetic sort if salary is equal. [A to Z]
	if (this.Salary == other.Salary)
	{
	    return this.Name.CompareTo(other.Name);
	}
	// Default to salary sort. [High to low]
	return other.Salary.CompareTo(this.Salary);
    }

    public override string ToString()
    {
	// String representation.
	return this.Salary.ToString() + "," + this.Name;
    }
}

class Program
{
    static void Main()
    {
	List<Employee> list = new List<Employee>();
	list.Add(new Employee() { Name = "Steve", Salary = 10000 });
	list.Add(new Employee() { Name = "Janet", Salary = 10000 });
	list.Add(new Employee() { Name = "Andrew", Salary = 10000 });
	list.Add(new Employee() { Name = "Bill", Salary = 500000 });
	list.Add(new Employee() { Name = "Lucy", Salary = 8000 });

	// Uses IComparable.CompareTo()
	list.Sort();

	// Uses Employee.ToString
	foreach (var element in list)
	{
	    Console.WriteLine(element);
	}
    }
}

Output

500000,Bill
10000,Andrew
10000,Janet
10000,Steve
8000,Lucy

CompareTo. Look again at the CompareTo method implementation in the Employee class. The method returns int—this indicates which Employee should be ordered first. In CompareTo, we want to sort by the Salary from highest to lowest.

However: If Salary is equal, we want to sort alphabetically. We check for equal Salary values, and in that case sort alphabetically.

In the Main method, we create a List of Employee instances. Each Employee has a Name and a Salary specified. Then, we invoke the Sort method on List. This uses the IComparable<Employee> implementation we added.

Result: When this program is run, the Employee instances are sorted first by Salary and then by Name.

List

Reverse sorts. What should you do if you want to sort in reverse order in the CompareTo method? For example, if you want to order the Employee instances from lowest to highest salary, you could simply reverse the order of the CompareTo expression.

Fragment that sorts on Salary: high to low

return other.Salary.CompareTo(this.Salary);

Sorts on Salary: low to high

return this.Salary.CompareTo(other.Salary);

Alternatives. There are alternative ways you can sort collections of objects by two properties. The easiest is probably the orderby clause in the query syntax in System.Linq. For more information on this, check out the LINQ page on this site.

LINQ Examples: System.Linq and ExtensionsOrderBy Clause

CompareTo and IComparable are often faster than LINQ and the orderby clause. The IComparable version reorders the elements in the original list, while the orderby clause will return an IEnumerable that you must copy into a new List.

List. There are other syntax forms available for sorting the List type. You can specify the Comparison delegate in the lambda expression syntax. In this case, you do not need to implement the IComparable interface at all.

Caution: This approach may be less robust and exhibit poorer object-orientation. But in many cases, it is acceptable.

Sort TupleSort List Method

Summary. Through this example program, we implemented the IComparable<T> interface on a class. Then we demonstrated that the List.Sort method uses this interface to sort an object collection.

Finally: We covered alternative methods of sorting objects and the drawbacks of these methods.


Related Links

Adjectives Ado Ai Android Angular Antonyms Apache Articles Asp Autocad Automata Aws Azure Basic Binary Bitcoin Blockchain C Cassandra Change Coa Computer Control Cpp Create Creating C-Sharp Cyber Daa Data Dbms Deletion Devops Difference Discrete Es6 Ethical Examples Features Firebase Flutter Fs Git Go Hbase History Hive Hiveql How Html Idioms Insertion Installing Ios Java Joomla Js Kafka Kali Laravel Logical Machine Matlab Matrix Mongodb Mysql One Opencv Oracle Ordering Os Pandas Php Pig Pl Postgresql Powershell Prepositions Program Python React Ruby Scala Selecting Selenium Sentence Seo Sharepoint Software Spellings Spotting Spring Sql Sqlite Sqoop Svn Swift Synonyms Talend Testng Types Uml Unity Vbnet Verbal Webdriver What Wpf