Apr 19, 2007

PropertyComparer for SORTING a Generic List

public class PropertyComparer<T>: IComparer<T>
{
private readonly System.Reflection.PropertyInfo _propertyInfo;
private readonly string _sortDirection;

public PropertyComparer(string sortDirection, string propertyToSort)
{
_sortDirection = sortDirection;
_propertyInfo = typeof(T).GetProperty(propertyToSort, System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.FlattenHierarchy | System.Reflection.BindingFlags.IgnoreCase);
}

public int Compare(T x, T y)
{
object xValue = _propertyInfo.GetValue(x, null);
object yValue = _propertyInfo.GetValue(y, null);
if ((_sortDirection == "Ascending"))
{
return System.Collections.Comparer.Default.Compare(xValue, yValue);
}
else
{
return System.Collections.Comparer.Default.Compare(yValue, xValue);
}
}
}

======================
protected void Page_Load(object sender, EventArgs e)
{
List
<Task> test = new List<Task>();
Task ta = new Task();
ta.TaskName = "Scheduling";
ta.Description = "Start of the Scheduling process to schedule processing of transcripts and press releases");
test.Add(ta);
test.Sort(new PropertyComparer<Task>("Ascending","TaskName"));
}

kick it on DotNetKicks.com

1 comment:

Unknown said...

You really shouldn't be using a string for the sort direction. It should be something like this.

public PropertyComparer(ListSortDirection sortDirection, string propertyToSort)