/// <summary>
/// RWilliams - 11/11/2008
/// Generic comparer class that allows use to sort
/// on a generic collection property/property
/// </summary>
/// <typeparam name="T">the generic type</typeparam>
public class ObjectComparer : IComparer
{
// Our private variables
private string propertyName = string.Empty;
private SortDirection sortDirection = SortDirection.Ascending;
/// <summary>
/// which direction should the sorting down asc or desc?
/// </summary>
public enum SortDirection: int
{
Ascending = 0,
Descending = 1
}
/// <summary>
/// the constructor collects the neccessart params, we might want
/// to add some properties too, if there is a need to.
/// </summary>
/// <param name="property"></param>
/// <param name="sortDirection"></param>
public ObjectComparer(string propertyName, SortDirection sortDirection)
{
this.propertyName = propertyName;
this.sortDirection = sortDirection;
}
#region IComparer Members
/// <summary>
/// Now lets do some sorting
/// </summary>
/// <param name="x">an object x of generic type</param>
/// <param name="y">an object y of generic type</param>
/// <returns>an int value that represents the results of the comparison</returns>
public int Compare(object x, object y)
{
// See the property could be anything, Lets use reflection and see
// if we can grab the property/property that needs to be sorted.
// There are multiple ways to go about doing this.
// - you could use
// 1. x.GetType().GetProperty(property).GetValue(x, null);
// 2. typeof(T).GetProperty(property).GetValue(x, null); if you have passed
// in a generic object "ObjectComparer<T>"
// 3. System.Reflection.PropertyInfo pi = typeof(T).GetProperty(property)
//NOTE: I assumed here that x & y are the same,
// if they arn't then split this code
// Patch - this is to support people that actually type ASC or DESC
// in their property names--arrggghhhhh
if (propertyName.ToUpper().EndsWith(" ASC"))
{
sortDirection = SortDirection.Ascending;
propertyName = propertyName.Replace(" ASC", string.Empty);
}
if (propertyName.ToUpper().EndsWith(" DESC"))
{
sortDirection = SortDirection.Descending;
propertyName = propertyName.Replace(" DESC", string.Empty);
}
//
System.Reflection.PropertyInfo pi = x.GetType().GetProperty(propertyName);
IComparable x1 = pi.GetValue(x, null) as IComparable;
IComparable y1 = pi.GetValue(y, null) as IComparable;
// we shall return and flip sort direction
return (sortDirection == SortDirection.Ascending)
? x1.CompareTo(y1) : y1.CompareTo(x1);
}
#endregion
}