.NET Sorting: Compare Just About Any Property of Any Object

Archimedes once claimed that given a lever long enough, a fulcrum strong enough, and a place to stand, he could move the world. (Archimedes also reportedly ran through the streets of Athens naked shouting Eureka when he discovered displacement, but that's another story.) Advanced techniques such as interfaces, reflection, and generics may not enable you to move the world, but they are sufficient tools for doing a lot of work, which is what Archimedes meant.

One such powerful tool that the .NET Framework provides is the generic interface IComparer. Implement IComparer and provide the type of object to compare, and .NET supports sorting any kind of collection of objects. Implement IComparer and fold in some reflection, and your IComparer will compare just about any property of any object. Using reflection won't yield a lightening fast sort, but the tradeoff for speed is flexibility.

Implementing IComparer

IComparer takes a parameter type T and two arguments of type T. Your job is to implement the comparison behavior and return -1 for x < y, 0 for x = y, and >0 for x > y. You can slightly enhance this basic comparison behavior by passing in a property name to the constructor, passing in an enumerated value to indicate sort direction, and using reflection to obtain access to the property value.

Listing 1 shows how you can specify the value of enumerated fields to reverse the results of the sort behavior:

The PropertyComparer class uses reflection to get the type information for the property passed into the PropertyComparer's constructor and attempts to call the property's CompareTo method (if it exists). If the property has a CompareTo method, the comparison will work. If no CompareTo method exists, the Compare method returns 0, which has a benign effect.

The key to understanding the PropertyComparer class lies in the boldfaced code of Listing 2. The first thing Compare does is get the PropertyInfo record for the x and y arguments. Next, it obtains the value of the property using the argument's x and y and the PropertyInfo record. Finally, it inspects the type of the property to determine how to call the Compare method implemented at the end of the class. The Compare method implemented has a where predicate that limits the types of the parameter K to those that implement IComparable. The reason for this is that IComparable types implement CompareTo.