Part 78 Sort a list of complex types in c#04:33

  • 0
Published on January 1, 2018

Code samples used in the demo

Slides

Link for csharp, asp.net, ado.net, dotnet basics, mvc and sql server video tutorial playlists

This is continuation to Part 77. Please watch Part 77, before proceeding.

To sort a list of complex types without using LINQ, the complex type has to implement IComparable interface and provide implementation for CompareTo() method. CompareTo() method returns an integer, and the meaning of the return value is shown below.
Return value greater than ZERO – The current instance is greater than the object being compared with.
Return value less than ZERO – The current instance is less than the object being compared with.
Return value is ZERO – The current instance is equal to the object being compared with.

Alternatively you can also invoke CompareTo() method. Salary property of the Customer object is int. CompareTo() method is already implemented on integer type, so we can invoke this method and return it’s value as shown below.
return this.Salary.CompareTo(obj.Salary);

public class Customer : IComparable[Customer]
{
public int ID { get; set; }
public string Name { get; set; }
public int Salary { get; set; }

public int CompareTo(Customer obj)
{
//if (this.Salary ] obj.Salary)
// return 1;
//else if (this.Salary [ obj.Salary)
// return -1;
//else
// return 0;

// OR, Alternatively you can also invoke CompareTo() method.
return this.Salary.CompareTo(obj.Salary);
}
}

If you prefer not to use the Sort functionality provided by the class, then you can provide your own by implementing IComparer interface. For example, if I want the customers to sorted by name instead of salary.
Step 1: Implement IComparer interface
public class SortByName : IComparer[Customer]
{
public int Compare(Customer x, Customer y)
{
return x.Name.CompareTo(y.Name);
}
}

Step 2: Pass an instance of the class that implements IComparer interface, as an argument to the Sort() method.
SortByName sortByName = new SortByName();
listCutomers.Sort(sortByName);

Enjoyed this video?
"No Thanks. Please Close This Box!"