Click here to Skip to main content
13,350,861 members (54,362 online)
Click here to Skip to main content
Add your own
alternative version


34 bookmarked
Posted 19 Aug 2005

A Simple and Generic sorting technique for your business object collection

, 19 Aug 2005
Rate this:
Please Sign up or sign in to vote.
This article discusses sorting of a user defined collection object based on any of the properties of the business entity.


Stop writing IComparer classes to sort your custom collections! This article discusses sorting of a user defined collection object based on any of the properties of the business entity. This sorting technique is generic for all the collection objects. You can sort your collection based on their properties.


For example consider the "Student" and "StudentCollection" classes:

public class Student
     string name="";
     public string Name
         get{return name;}
         set{name = value;}
     int id=0;
     public int Id
         get{return id;}
         set{id = value;}
     DateTime dob=DateTime.MinValue;
     public DateTime DOB
         get{return dob;}
         set{dob = value;}
     public Student(string name,int id,DateTime Dob)
    { = name; = id;
         this.dob = Dob;
 public class StudentCollection : CollectionBase
     public StudentCollection()
     //Other code ……..
     // ...

Student collection consists of Student object collection. Student entity consists of three properties namely, name, id and Dob. Suppose you want to sort the collection based on the Student's Name or Id or DOB, we need to write the Comparer class for each user defined collection as follows.

Usual way of sorting objects using IComparer and IComparable interfaces

class StudentComparer : IComparer
    private int intCompType;
    public StudentComparer (int sortOrder)
        intCompType = sortOrder;
    public int Compare(object x,object y)
            case (int)enuSortOrder.NameAsc:
                return ((Student)x).Name.CompareTo(((Student)y).Name);
            case (int)enuSortOrder.NameDesc:
                return ((Student)y).Name.CompareTo(((Student)x).Name);


For StudentCollection we need a StudentComparer class and for ProductCollection we need a ProductComparer class…and so on…. To avoid these cumbersome coding, I wrote a generic "SortableCollectionBase" class that can be used to sort any custom collection object without tedious coding.


How it works?

SortableCollectionBase class uses "GenericComparer" class for sorting. "GenericComparer" class implements IComparer interface and compares the objects based on the public property (Sort Column) of the class type dynamically irrespective of the collection.

GenericComparer class

/// <summary>
/// This class is used to compare any 
/// type(property) of a class.
/// This class automatically fetches the 
/// type of the property and compares.
/// </summary>
public sealed class GenericComparer:IGenericComparer 
    /// <summary>
    /// Sorting order
    /// </summary>
    public enum SortOrder
        Ascending = 0,
        Descending = 1
    Type objectType;
    /// <summary>
    /// Type of the object to be compared.
    /// </summary>
    public Type ObjectType
        get{return objectType;}set{objectType = value;}
    string sortcolumn = "";
    /// <summary>
    /// Column(public property of the class) to be sorted.
    /// </summary>
    public string SortColumn
        get{return sortcolumn;}set{sortcolumn = value;}
    int sortingOrder = 0;
    /// <summary>
    /// Sorting order.
    /// </summary>
    public int SortingOrder
        get{return sortingOrder;}set{sortingOrder = value;}
    /// <summary>
    /// Compare interface implementation
    /// </summary>
    /// <param name="x">Object 1</param>
    /// <param name="y">Object 2</param>
    /// <returns>Result of comparison</returns>
    public int Compare(object x, object y)
        //Dynamically get the protery info 
        //based on the protery name
        PropertyInfo propertyInfo = 
        //Get the value of the instance
        IComparable obj1 = 
              (IComparable)propertyInfo.GetValue(x,null) ;
        IComparable obj2 = 
              (IComparable)propertyInfo.GetValue(y,null) ;
        //Compare based on the sorting order.
        if(sortingOrder == 0)
        return ( obj1.CompareTo(obj2) );
        return ( obj2.CompareTo(obj1) );

SortableCollectionBase class

/// <summary>
/// Abstract implementation of Sortable collection.
/// </summary>
public abstract class SortableCollectionBase : 
    string sortcolumn="";
    public string SortColumn
        get{return sortcolumn;}
        set{sortcolumn = value;}
    GenericComparer.SortOrder sortingOrder = 
    public GenericComparer.SortOrder SortingOrder
        get{return sortingOrder;}set{sortingOrder = value;}
    Type sortObjectType;
    public Type SortObjectType
        get{return sortObjectType;} set{sortObjectType = value;} 
    public virtual void Sort() 
        if(sortcolumn == "") 
            throw new Exception("Sort column required."); 
        if(SortObjectType == null) 
            throw new Exception("Sort object type required."); 
        IGenericComparer sorter = new GenericComparer();
        sorter.ObjectType = sortObjectType;
        sorter.SortColumn = sortcolumn;
        sorter.SortingOrder = (int)sortingOrder;

How to use SortableCollectionBase class?

Using SortableCollectionBase is simple and effortless. Just inherit your custom collection class from SortableCollectionBase class and in the constructor set the SortableObjectType property. Now your class becomes sortable.

For example

/// <summary>
/// Note : This student collection 
/// inherhits SortableCollectionBase
/// In the constructor set the 
/// SortObjectType for sorting.
/// </summary>
public class StudentCollection : 
    public StudentCollection()
        //In your collection class 
        //constructor add this line.
        //set the SortObjectType for sorting.
        base.SortObjectType = typeof(Student);
    public Student this[ int index ] 
            return( (Student) List[index] );
            List[index] = value;
    public int Add( Student value ) 
        return( List.Add( value ) );
    public int IndexOf( Student value ) 
        return( List.IndexOf( value ) );
    public void Insert( int index, Student value ) 
        List.Insert( index, value );

How to sort?

To sort your custom collection call the "Sort()" method. Note: Make sure that you have set the "SortColumn" property before calling the "Sort()" method. "SortColumn" is the property of the business entity based on which the collection will be sorted. In this case SortColumn can be "name", "id" or "Dob".

StudentCollection Students = new StudentCollection();
Students.Add(new Student("Sai",5,new DateTime(1914,10,4)));
Students.Add(new Student("Sree",1,new DateTime(1980,10,4)));
Students.Add(new Student("Sow",3,new DateTime(2000,4,1)));
Students.Add(new Student("Zaheer",2,new DateTime(1978,1,27)));
Students.SortColumn = "Name";
Students.SortingOrder = 
dataGrid1.DataSource = Students;


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

Web Developer
India India
No Biography provided

You may also be interested in...


Comments and Discussions

QuestionGenerics? Pin
tmag25-Feb-08 7:34
membertmag25-Feb-08 7:34 
AnswerRe: Generics? Pin
razaross21-Dec-09 14:23
memberrazaross21-Dec-09 14:23 
QuestionThe data doesn't show up Pin
hschan824-Sep-07 13:12
memberhschan824-Sep-07 13:12 
GeneralVery good - Simple and useful... Pin
NarasinhaSource1-Aug-07 13:38
memberNarasinhaSource1-Aug-07 13:38 
GeneralWorks great in VS2003. Maybe an update for VS2005 Pin
hfourie29-Apr-07 1:03
memberhfourie29-Apr-07 1:03 
GeneralGreat Post Pin
SamStange13-Feb-07 8:22
memberSamStange13-Feb-07 8:22 
GeneralWorks great! Pin
Koen Zomers21-Aug-06 7:19
memberKoen Zomers21-Aug-06 7:19 
I've made a slight modification so it works with generic methods in .NET 2.0. Works great now! I don't have to write a collection class for each business object anymore. Just one does the trick. Thanks for this great piece of code.
General:) Pin
Daniel@SA10-Apr-06 0:16
memberDaniel@SA10-Apr-06 0:16 
QuestionSorting on multiple properties at once? Pin
versat14747-Sep-05 7:29
memberversat14747-Sep-05 7:29 
AnswerRe: Sorting on multiple properties at once? Pin
Daniel Brown (SmartSoft)22-Feb-06 17:22
memberDaniel Brown (SmartSoft)22-Feb-06 17:22 
QuestionHow to Check Performance Pin
anig123425-Aug-05 1:43
memberanig123425-Aug-05 1:43 
GeneralPerformance Pin
Sean Winstead20-Aug-05 14:21
memberSean Winstead20-Aug-05 14:21 
GeneralRe: Performance Pin
SreeKrishna20-Aug-05 19:51
memberSreeKrishna20-Aug-05 19:51 
GeneralRe: Performance Pin
caractacus23-Aug-05 23:07
membercaractacus23-Aug-05 23:07 

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
Web01 | 2.8.180111.1 | Last Updated 20 Aug 2005
Article Copyright 2005 by SreeKrishna
Everything else Copyright © CodeProject, 1999-2018
Layout: fixed | fluid