using System;
using System.Collections.Generic;
using System.Text;
using System.ComponentModel;
namespace IReaper{
public class SortCompare<T> : IComparer<T>
{
PropertyDescriptor m_property = null;
ListSortDirection m_direction = ListSortDirection.Ascending;
/// <summary>
/// Course
/// </summary>
/// <param name="propDesc"></param>
/// <param name="direction"></param>
public SortCompare(PropertyDescriptor propDesc, ListSortDirection direction)
{
this.m_property = propDesc;
this.m_direction = direction;
}
#region IComparer<T>
int IComparer<T>.Compare(T x, T y)
{
object xValue = this.m_property.GetValue(x);
object yValue = this.m_property.GetValue(y);
int retValue = 0;
if (xValue is IComparable) // Can ask the x value
{
retValue = ((IComparable)xValue).CompareTo(yValue);
}
else if (yValue is IComparable) //Can ask the y value
{
retValue = ((IComparable)yValue).CompareTo(xValue);
}
// not comparable, compare String representations
else if (!xValue.Equals(yValue))
{
retValue = xValue.ToString().CompareTo(yValue.ToString());
}
if (this.m_direction == ListSortDirection.Ascending)
{
return retValue;
}
else
{
return retValue * -1;
}
}
#endregion
}
}
|