Tuesday, July 24, 2007

Generic List Sorting

I have a custom entity that I have created within my web application and I am binding it to my DataGrid (I know I should be using a GridView, but that change will come later...). Previously the data was being retrieved into a DataTable, so when I needed to sort, I could just apply a DataView to the DataTable passing the appropriate sort filter and I was set. But with the Generic list, it was not that simple. I did a little research on Delegates and Predicates to maybe solve my problem, but then I was creating custom code for each and every list that I needed to perform this on. However, in my Google searching I discovered this article, Sorting GridView Using IComparer by TheDotNetGuy and he is a using a GenericComparer class to do exactly what I wanted. I really liked the flexibility that this solution provided.

using System;
using System.Web.UI.WebControls;
using System.Collections.Generic;
using System.Reflection;

public class GenericComparer<T> : IComparer<T>
    private SortDirection _sortDirection;
    private string _sortExpression;

    /// <summary>
    /// Direction in which to sort.
    /// </summary>
    public SortDirection SortDirection
        get { return this._sortDirection; }
        set { this._sortDirection = value; }

    public GenericComparer(string sortExpression, SortDirection sortDirection)
        this._sortExpression = sortExpression;
        this._sortDirection = sortDirection;

    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);

As an example, I could sort a list of personnel by last name as follows:
    List<MyApp.Entities.Personnel> personnel = MyApp.Entities.Personnel.Load();
    personnel.Sort(new GenericComparer<MyApp.Entities.Personnel>("LastName",SortDirection.Ascending);

Monday, July 23, 2007


I ran across the following ASP.NET AJAX links over the last couple of weeks that I found interesting and useful, so I thought I would pass them along.