# Saturday, March 10, 2007
« HTML label element | Main | Testing the test code, not the productio... »
I needed to implement sorting in one of our applications that contained a grid with multiple properties.  Normally in .NET 1.1 most people would throw the data into a DataSet and be on their way, but I already had a domain model with some nice POCOs, so I though why bother to load a dataset just to support sorting on a few elements?  I started to write a an IComparer but then I realized I would have to do it 6 more times for each property.  No thanks.

I decided to implement a super easy string property comparer that would get the property it needed to compare using reflection.

/// <summary>
/// Generic and reusable IComparer for string based properties.
/// </summary>
public class StringPropertyComparer : IComparer
{
    private string m_propertyName;
    private Type m_declaringClass;

    public StringPropertyComparer(Type declaringClass, string propertyName)
    {
        m_declaringClass = declaringClass;
        m_propertyName = propertyName;
    }

    private string getPropertyValue(object instance)
    {
        PropertyInfo info = m_declaringClass.GetProperty(m_propertyName, typeof(string));
        return (string) info.GetValue(instance, null);
    }

    public int Compare(object lhsObj, object rhsObj)
    {
        string lhs = getPropertyValue(lhsObj);
        string rhs = getPropertyValue(rhsObj);

        return ((new CaseInsensitiveComparer()).Compare(lhs, rhs));
    }
}

This could really be expanded to support multiple types besides strings, support asc and desc, and to support ordering by n+1 properties.  Perhaps some other day...  This works for now.


Comments are closed.