5,534,119 members and growing! (17,080 online)
Email Password   helpLost your password?
Languages » C# » General     Intermediate

Sorting Generic Collections

By Saravanan M

Here is an advanced sortable list that can be used in ASP.Net Pages.
C# 2.0, C#, Windows, .NET, .NET 2.0, ASP.NET, VS2005, Visual Studio, Dev

Posted: 12 Feb 2007
Updated: 15 Feb 2007
Views: 24,468
Bookmarked: 27 times
Announcements
Want a new Job?



Search    
Advanced Search
Sitemap
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 has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here

About the Author

Saravanan M


He has been programming for 6+ years in Microsoft Technologies. He started his programming with C. Now He works for Netkode Solutions, India. http://www.netkode.com. He wrote several network applications like telephone capturing, RS232 network based applications. He is a MCP Professional and he loves Microsoft Technologies.

Occupation: Web Developer
Location: India India

Other popular C# articles:

Article Top
Sign Up to vote for this article
You must Sign In to use this message board.
FAQ FAQ Noise ToleranceSearch Search Messages 
 Layout  Per page   
 Msgs 1 to 11 of 11 (Total in Forum: 11) (Refresh)FirstPrevNext
Subject  Author Date 
GeneralGood One....memberJahnavee19:28 15 Feb '07  
Generalsearch in gen collectionmember852y3agnna8:35 14 Feb '07  
GeneralThanksmembercykophysh3912:21 13 Feb '07  
Questionfinding items in Generic Collectionsmember852y3agnna11:51 13 Feb '07  
AnswerRe: finding items in Generic CollectionsmemberChris_Martinez9:52 20 Feb '07  
GeneralGood article, but....memberRob Minter8:05 13 Feb '07  
GeneralRe: Good article, but....memberSaravanan M0:45 14 Feb '07  
GeneralSort on Two fieldsmemberGamersWanted4:38 13 Feb '07  
GeneralRe: Sort on Two fieldsmemberSaravanan M19:21 13 Feb '07  
GeneralRe: Sort on Two fieldsmembermladen0:16 14 Feb '07  
GeneralRe: Sort on Two fieldsmemberChris_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 M
Everything else Copyright © CodeProject, 1999-2008
Web10 | Advertise on the Code Project