Click here to Skip to main content
6,633,937 members and growing! (24,570 online)
Email Password   helpLost your password?
Languages » C# » General     Intermediate License: The Code Project Open License (CPOL)

Sorting Generic Collections

By Saravanan Muthiah

Here is an advanced sortable list that can be used in ASP.Net Pages.
C# 2.0, Windows, .NET 2.0, ASP.NET, WebForms, VS2005, Dev
Posted:12 Feb 2007
Updated:15 Feb 2007
Views:32,090
Bookmarked:36 times
Announcements
Loading...
 
Search    
Advanced Search
Add to IE Search
printPrint   add Share
      Discuss Discuss   Broken Article?Report  
10 votes for this article.
Popularity: 3.71 Rating: 3.71 out of 5
1 vote, 10.0%
1
1 vote, 10.0%
2
1 vote, 10.0%
3
2 votes, 20.0%
4
5 votes, 50.0%
5
Sample image

Introduction

By default the List<T> class supports the following sort methods Sort(Icomparer<T>) and Sort(Comparison<T>). This does not help us to sort our collections by datatype of the property. This artical help us to fill the above gap.

A User Class

Let us have a simple User class that exposes Id, UserName, JoinDate, UserType and Active Status properties. Let us take the simple List<T> Collection class to hold the list of User objects. The SortableList<T> inherits the List<T> generic class. The Sort method takes to arguments. Let us say propertyName and ascending.

public enum UserTypeEnum
{
    Manager,
    ProjectLead,
    TeamLead,
    SeniorSoftwareEngineer,
    SoftwareEngineer
}
/// <summary />

/// Summary description for User

/// </summary />

public class User
{
    public User(int id, string userName,DateTime joinDate, 
               UserTypeEnum userType, bool isActive)
    {
        this.id = id;
        this.userName = userName;
        this.joinDate = joinDate;
        this.userType = userType;
        this.isActive = isActive;
    }

    private int id;

    public int Id
    {
        get { return id; }
        set { id = value; }
    }
    private string userName = string.Empty ;

    public string UserName
    {
        get { return userName; }
        set { userName = value; }
    }
    private DateTime joinDate = DateTime.MinValue;

    public DateTime JoinDate
    {
        get { return joinDate; }
        set { joinDate = value; }
    }
    private UserTypeEnum userType = UserTypeEnum.SoftwareEngineer;

    public UserTypeEnum UserType
    {
        get { return userType; }
        set { userType = value; }
    }
    private bool isActive = false;

    public bool IsActive
    {
        get { return isActive; }
        set { isActive = value; }
    }
}

Sortable List:

public class SortableList<T>: List<T>
{
    private string _propertyName;
    private bool _ascending;

    public void Sort(string propertyName, bool ascending)
    {
        //Flip the properties if the parameters are the same

        if (_propertyName == propertyName && _ascending == ascending)
            _ascending = !ascending;
        //Else, new properties are set with the new values

        else
        {
            _propertyName = propertyName;
            _ascending = ascending;
        }

        PropertyDescriptorCollection properties
                                = TypeDescriptor.GetProperties(typeof(T));
        PropertyDescriptor propertyDesc = properties.Find(propertyName, true);

        // Apply and set the sort, if items to sort

        PropertyComparer<T> pc = new PropertyComparer<T>(propertyDesc, 
                  (_ascending) ? ListSortDirection.Ascending : 
                   ListSortDirection.Descending);
        this.Sort(pc);
    }
The GetProperties of TypeDescriptor class returns the collection of properties on a component or type and Find method of PropertyDescriptorCollection returns the PropertyDescriptor with the specified name, using a Boolean to indicate whether to ignore case. A PropertyDescriptor with the specified name, or a null reference if the property does not exist.

Now, we can use any property comparer class to compare the values of the property. Here I use PropertyComaparer<T> class that wrote by Rockford Lhotka in MSDN.

PropertyComparer builds on a comparison algorithm based built by Rockford Lhotka and turns it into a generic property comparer for any type. (Note: While a detailed analysis of the comparer is beyond the scope of this article, a brief discussion will suffice, although I urge you to read Rocky's great article and inspect the code sample).

That's it! We are ready to implement this sortable list into our ASP.NET pages.

Code Behind File:

protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            SortableList<user> list = BuildList();
            Cache.Insert("Users", list, null,
                System.Web.Caching.Cache.NoAbsoluteExpiration,
                System.Web.Caching.Cache.NoSlidingExpiration,
                System.Web.Caching.CacheItemPriority.High,
                null);
            UsersGridView.DataSource = list;
            UsersGridView.DataBind();
        }
    }
    protected void UsersGridView_PageIndexChanging(object sender, 
                                                   GridViewPageEventArgs e)
    {
        SortableList<user> list = Cache["Users"] as SortableList<user>;

        UsersGridView.PageIndex = e.NewPageIndex;
        UsersGridView.DataSource = list;
        UsersGridView.DataBind();
    }
    protected void UsersGridView_Sorting(object sender, 
                                         GridViewSortEventArgs e)
    {
        SortableList<user> list = Cache["Users"] as SortableList<user>;

        list.Sort(e.SortExpression, 
                  (e.SortDirection == SortDirection.Ascending));
        //Add the sorted collection back to the cache

        Cache.Insert("Users", list, null,
                System.Web.Caching.Cache.NoAbsoluteExpiration,
                System.Web.Caching.Cache.NoSlidingExpiration,
                System.Web.Caching.CacheItemPriority.High,
                null);
        
        UsersGridView.DataSource = list;
        UsersGridView.DataBind();
    }

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

Saravanan Muthiah


Member
He has been programming for 8+ years in Microsoft Technologies. He started his programming with C. Now He works for Quadwave Consulting, Bangalore. He has written several network applications like call capturing, RS232 network based applications. He is a MCP Professional and he loves Microsoft Technologies.
Occupation: Software Developer (Senior)
Location: India India

Other popular C# articles:

Article Top
You must Sign In to use this message board.
FAQ FAQ 
 
Noise Tolerance  Layout  Per page   
 Msgs 1 to 11 of 11 (Total in Forum: 11) (Refresh)FirstPrevNext
GeneralGood One.... PinmemberJahnavee19:28 15 Feb '07  
Generalsearch in gen collection Pinmember852y3agnna8:35 14 Feb '07  
GeneralThanks Pinmembercykophysh3912:21 13 Feb '07  
Questionfinding items in Generic Collections Pinmember852y3agnna11:51 13 Feb '07  
AnswerRe: finding items in Generic Collections PinmemberChris_Martinez9:52 20 Feb '07  
GeneralGood article, but.... PinmemberRob Minter8:05 13 Feb '07  
GeneralRe: Good article, but.... PinmemberSaravanan M0:45 14 Feb '07  
GeneralSort on Two fields PinmemberGamersWanted4:38 13 Feb '07  
GeneralRe: Sort on Two fields PinmemberSaravanan M19:21 13 Feb '07  
GeneralRe: Sort on Two fields Pinmembermladen0:16 14 Feb '07  
GeneralRe: Sort on Two fields PinmemberChris_Martinez9:42 20 Feb '07  

General General    News News    Question Question    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

PermaLink | Privacy | Terms of Use
Last Updated: 15 Feb 2007
Editor: Chris Maunder
Copyright 2007 by Saravanan Muthiah
Everything else Copyright © CodeProject, 1999-2009
Web10 | Advertise on the Code Project