Click here to Skip to main content
13,043,092 members (60,545 online)
Click here to Skip to main content
Add your own
alternative version


41 bookmarked
Posted 12 Feb 2007

Sorting Generic Collections

, 15 Feb 2007
Rate this:
Please Sign up or sign in to vote.
Here is an advanced sortable list that can be used in ASP.Net Pages.
Sample image


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
/// <summary />
/// Summary description for User
/// </summary />
public class User
    public User(int id, string userName,DateTime joinDate, 
               UserTypeEnum userType, bool isActive)
    { = 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
            _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 : 
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,
            UsersGridView.DataSource = list;
    protected void UsersGridView_PageIndexChanging(object sender, 
                                                   GridViewPageEventArgs e)
        SortableList<user> list = Cache["Users"] as SortableList<user>;

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

                  (e.SortDirection == SortDirection.Ascending));
        //Add the sorted collection back to the cache
        Cache.Insert("Users", list, null,
        UsersGridView.DataSource = list;


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


About the Author

Saravanan Muthiah
India India
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.

You may also be interested in...

Comments and Discussions

GeneralGood One.... Pin
Jahnavee15-Feb-07 18:28
memberJahnavee15-Feb-07 18:28 
Generalsearch in gen collection Pin
852y3agnna14-Feb-07 7:35
member852y3agnna14-Feb-07 7:35 
GeneralThanks Pin
cykophysh3913-Feb-07 11:21
membercykophysh3913-Feb-07 11:21 
Questionfinding items in Generic Collections Pin
852y3agnna13-Feb-07 10:51
member852y3agnna13-Feb-07 10:51 
AnswerRe: finding items in Generic Collections Pin
Chris_Martinez20-Feb-07 8:52
memberChris_Martinez20-Feb-07 8:52 
It's already in the .NET Framework right out of the box. See Array.Find<T> or List<T>.Find<T>. There are also the FindAll<T> methods.

If you want to perform a binary search, use the respective BinarySearch<T> methods. In the article I wrote discussing Object Sorting, it explains/defines how to use a generic IComparer<T> implementation to sort objects with any varying amount of complexity (1 property, 2 properties, etc) without using Reflection. This same comparer can be used to perform binary searches (assuming the list is already sorted).

Best regards,

"My logic is undeniable!"

GeneralGood article, but.... Pin
Rob Minter13-Feb-07 7:05
memberRob Minter13-Feb-07 7:05 
GeneralRe: Good article, but.... Pin
Saravanan M13-Feb-07 23:45
memberSaravanan M13-Feb-07 23:45 
GeneralSort on Two fields Pin
GamersWanted13-Feb-07 3:38
memberGamersWanted13-Feb-07 3:38 
GeneralRe: Sort on Two fields Pin
Saravanan M13-Feb-07 18:21
memberSaravanan M13-Feb-07 18:21 
GeneralRe: Sort on Two fields Pin
mladen13-Feb-07 23:16
membermladen13-Feb-07 23:16 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Permalink | Advertise | Privacy | Terms of Use | Mobile
Web02 | 2.8.170713.1 | Last Updated 15 Feb 2007
Article Copyright 2007 by Saravanan Muthiah
Everything else Copyright © CodeProject, 1999-2017
Layout: fixed | fluid