Skip to main content

DotNet: Generic Sorting Class

Recently, I was searching for a generic sorting approach on dotnet List. Many articles (Like one, two..etc) were suggesting standard way of creating IComparer implementer class and using that with generic list (List <T>) in our application. Writing IComparer class for every business object not only take huge time also create challenges in code management when it grow considerably. So, here is simple and effective generic sorting class which can be used with any custom business object and can be sorted on any one of its properties.

All you have to do is, copy paste the complete code in to a new .cs file.

using System;
using System.Collections.Generic;
using System.Text;
using System.Reflection;

namespace Srushti.Business
public class GenericComparer<T> : IComparer<T>
string _propName = string.Empty;
bool _sortDirection = true;
public GenericComparer(string propertyName, bool SortAscending)
_propName = propertyName;
_sortDirection = SortAscending;

private int CompareAsc(object o1, object o2)
if (o1 is IComparable)
return ((IComparable)o1).CompareTo(o2);
else if (o1.Equals(o2))
return 0;
return o1.ToString().CompareTo(o2);
#region IComparer<T> Members

public int Compare(T x, T y)
PropertyInfo pi = x.GetType().GetProperty(_propName);
object o1 = pi.GetValue(x, null);

pi = y.GetType().GetProperty(_propName);
object o2 = pi.GetValue(y, null);

if (_sortDirection == false)
return CompareAsc(o1, o2) * -1;
return CompareAsc(o1, o2);

...and start consuming it as shown below. You have to supply, property name (as String) on which you want to sort the list and sorting direction (Boolean, true for ascending and false for descending) to GenericComparer() constructor.

private void Form1_Load(object sender, EventArgs e)
List empList = new List();
empList.Add(new Employee() { ID = 1, Name = "Three" });
empList.Add(new Employee() { ID = 2, Name = "Two" });
empList.Add(new Employee() { ID = 3, Name = "One" });

/*** Generic Comparer ***/
empList.Sort(new GenericComparer("Name", true));

foreach (Employee em in empList)

public class Employee
public int ID { get; set; }
public string Name { get; set; }

Please Note: Class properties with complex data types like DateTime, Nullable might require special attention.


Popular posts from this blog

Windows forgets visual effects settings on log-out or reboot for non-administrator account

Steps given here worked for me with Windows 7 SP1. Hope you may find it useful.

Start -> Run-> cmd (press enter) -> type SystemPropertiesPerformance.exeThis gets you the "System Properties" window, go to  Advanced tab -> Performance Settings -> Visual Effects tab and choose "Adjust for best performance" and click OK. Note: While doing all these UAC doesn't show-up as all changes you are doing will be saved in your logged-in profile account.

Reference material used:

Feel free to comment your findings.

Why Akbar was Great?

I have fanatical interest to be acquainted with what made Indian emperors take influential decisions during their reign. Few great kings’ valuable decisions created a remarkable history.

When Akbar accepts the marriage proposal of Hindu King (Bharmal of Amer), he wishes to make an attempt to set an example for two culture and religions and convey the message of peace. Later, destiny takes him to the critical path of life having most depraved political and family oriented problems. Being a true great emperor, Akbar learns and conclude challenges by demonstrating his exceptional leadership qualities. With his verdicts, Akbar stands as an incomparable king of all time. “Jodha Akbar” – brings 16th-century incidents to life and shows beginning part of Akbar’s married life which was, in fact, a deal for political gain. This decision slowly unleashes Akbar’s loving life, internal dreadful politics, painfully desirous people around him and betraying family members.

Jalaluddin Mohammad Akbar is…

Windows Service or Windows Task Scheduler?

Are you planning to create long running background process (in C#) and thinking to build a Windows service?

Then wait for a moment!

Windows Task scheduler (Start->Programs->Accessories-> System Tools-> Task Scheduler) can also be a decent choice!

"Windows Vista and higher windows (server) operating systems are offering matured Task scheduler with many advancements like Triggers, Actions, Conditions, failure recovery, email notifications, security and much more."
Its obvious that many programmers think Windows Service is easy to maintain and what it can do, task scheduler can’t. But now, it’s time to look at Windows Task Scheduler [also at Microsoft white paper] and see what great features it is offering.

When to go for Windows Service?
Okay, let me try to answer this popular question in one line. 

Windows Service is suitable for receiving service request 'anytime' and process 'instantly'.

Just think of anti-virus scanner, network port activity tracker…