Sorting a List of Objects on Multiple Properties (C#)

Mike

There seem to be a few posts out there on how to accomplish the task of sorting a list of objects on more than one property.  My reason for posting this solution is it seems many of the options presented are really more complicated than they need to be.  In fact sorting on two properties can be done with just one line of code using the conditional operator.

This solution is being demonstrated in C# .NET but the same model can be followed using any language that supports a Sort method that accepts a delegate as a parameter.

In my example I will use two objects… object1 and object2.  Both of type ObjectType .  This type of object has two kinds of properties we will be sorting by… propertyA and propertyB.


//Sorting on two object properties
list.Sort(delegate(ObjectType object1, ObjectType object2)
{

return object1.propertyA.CompareTo(object2.propertyA) != 0
? object1.propertyA.CompareTo(object2.propertyA)
:  object1.propertyB.CompareTo(object2.propertyB);

});

Tags: , , ,

Comments are closed.