wayne on January 15, 2008
Great example of sorting a Generic.List<T> collection of objects can be found here. For future reference for myself, here is a class that can be reused in future projects whenever I need to sort a collection of custom objects:
/// <summary>
/// The generic comparer class allows for sorting on a generic collections property fields
/// </summary>
/// <typeparam name="T">An object</typeparam>
public class GenericComparer<T> : IComparer<T>
{
/// <summary>
/// Creates a new instance of the GenericComparer class
/// </summary>
/// <param name="sortExpression">A string expression of the field to sort</param>
/// <param name="sortDirection">A SortDirection value to indicate
/// Ascending or Descending sort</param>
public GenericComparer(string sortExpression, SortDirection sortDirection)
{
this.SortExpression = sortExpression;
this.SortDirection = sortDirection;
}
/// <summary>
/// Private container for the Sort Direction
/// </summary>
private SortDirection sortDirection;
/// <summary>
/// Private container for the expression used for the sort
/// </summary>
private string sortExpression;
/// <summary>
/// The expression to use during the sort (in this case, the Generic objects field name)
/// </summary>
public string SortExpression
{
get { return sortExpression; }
set { sortExpression = value; }
}
/// <summary>
/// The direction to perform the sort
/// </summary>
public SortDirection SortDirection
{
get { return this.sortDirection; }
set { this.sortDirection = value; }
}
/// <summary>
/// Performs the sort on the supplied objects
/// </summary>
/// <example>
/// The following example shows how to implement and use this class:
/// <![CDATA[
/// using System.Collections.Generic;
/// public class MyClass {
/// public void PerformSort() {
/// List<MyGenericObject> items = MyDataObject.GetObjects();
/// items.Sort(new GenericComparer<MyGenericObject>(SortExpression, SortDirection));
/// }
/// }
/// ]]>
/// </example>
/// <param name="x">The first object</param>
/// <param name="y">The second object</param>
/// <returns>An int value that specifies the result of the comparison</returns>
public int Compare(T x, T y)
{
PropertyInfo propertyInfo = typeof(T).GetProperty(SortExpression);
IComparable obj1 = (IComparable)propertyInfo.GetValue(x, null);
IComparable obj2 = (IComparable)propertyInfo.GetValue(y, null);
if (SortDirection == SortDirection.Ascending)
return obj1.CompareTo(obj2);
else
return obj2.CompareTo(obj1);
}
}