Introduction
This article is about a simple PropertyComparer
class that can be used to sort collections of objects by property of the objects in the collection:
using System;
using System.Collections;
using System.Collections.Generic;
using System.Reflection;
using System.Web.UI.WebControls;
namespace yourNamespace
{
public class PropertyComparer<T> : IComparer<T>
{
private PropertyInfo property;
private SortDirection sortDirection;
public PropertyComparer(string sortProperty, SortDirection sortDirection)
{
property = typeof (T).GetProperty(sortProperty);
Utils.AssertIsNotNull(
string.Format("Property {0} not found on type {1}", sortProperty,
typeof (T).FullName), sortProperty);
this.sortDirection = sortDirection;
}
public int Compare(T x, T y)
{
object valueX = property.GetValue(x, null);
object valueY = property.GetValue(y, null);
if (sortDirection == SortDirection.Ascending)
{
return Comparer.Default.Compare(valueX, valueY);
}
else
{
return Comparer.Default.Compare(valueY, valueX);
}
}
}
}
Usage
Here is an example of using the PropertyComparer
to sort a collection of objects:
public class ObjectInCollectionType
{
private string text = Guid.NewGuid().ToString();
public string Text
{
get { return text; }
set { text = value; }
}
}
public class TestPropertyComparer
{
public static void Test()
{
List<ObjectInCollectionType> myList = new List<ObjectInCollectionType>();
myList.Add(new ObjectInCollectionType());
myList.Add(new ObjectInCollectionType());
myList.Add(new ObjectInCollectionType());
myList.Add(new ObjectInCollectionType());
myList.Sort(new PropertyComparer<ObjectInCollectionType>
("Text", SortDirection.Ascending));
}
}
Happy programming.
History
- 1st November, 2006: Initial post
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.