c#: Sorting List of Complex Type or an Object using IComparable

To do sorting with List<T> of your own object type you need to implement IComparable<T> interface into the class itself. So when you have a List of the object you can easily call listOfObject.Sort() to sort the content of that list.

For example: imagine you have a Class Schedule for work schedule and that class have 2 properties which is  WorkDay and Shift. Both properties are a complex type or i should say a struct of itself and each of those have their own members and properties. Now if you’re going to sort a list of Schedule (List) and you have sort it based on the value of  it’s properties, for this example we want to sort it based on WorkDay and Shift. To be able to do that we need to implement IComparable<T> interface on each of the members of Schedule object and the Schedule object itself.

According to documentation the IComparable<T> interface defines generalized comparison method that a value type or class implements to create a type-specific comparison method for ordering or sorting its instances.

WorkDay class has two properties; Day int dan DayName string. Day is an integer that will be use to do comparison and DayName is the name of the day in string.WorkDay class needs to implement IComparable<T> interface where T is WorkDay and implement CompareTo method. The method CompareTo must return an Int32 with three possible values such as:

  • lest than zero, when the current object precedes the object specified by the CompareTo method in the sort order.
  • zero, the current instance occurs in the same position in the sort order as the object specified by the CompareTo method argument.
  • more than zero, the current instance follows the object specified by the CompareTo method argument in the sort order.

In this example we’re going to compare the Day property which of type int, with simple if else and logical operators would do the trick to figure out whether current instance of the object precedes or follows the object in the CompareTo method argument. Same principle also applies to Shift object, as for the Schedule object we simply call each property CompareTo methods inside Schedule.CompareTo and returns the result.

icomparable result
work schedule icomparable

Here’s the source code on gist and a github repo for this tutorial.

Tinggalkan Balasan

Isikan data di bawah atau klik salah satu ikon untuk log in:

Logo WordPress.com

You are commenting using your WordPress.com account. Logout /  Ubah )

Foto Google+

You are commenting using your Google+ account. Logout /  Ubah )

Gambar Twitter

You are commenting using your Twitter account. Logout /  Ubah )

Foto Facebook

You are commenting using your Facebook account. Logout /  Ubah )

w

Connecting to %s