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);
 
 
5 comments:
Works great - thanks for the post!
Works great! Any ideas on sorting by more than one field at a time?
Such As Last Name then First Name?
Saiba,
I would suggest that you leverage the power of LINQ and do an OrderBy expression followed with a ThenBy expression. Please see http://msdn.microsoft.com/en-us/library/bb534743.aspx for more information.
Or if you cannot leverage LINQ, then try the recursive example shown here: http://www.rosscode.com/blog/index.php?title=generic_multiple_sorting_for_typed_colle&more=1&c=1&tb=1&pb=1
Hope that helps.
Thanks you so much ! working perfectly. Searching a lot and finally got the working version . :-)
Bind gridview to generic list and sorting in C#.
Post a Comment