Click here to Skip to main content
13,003,589 members (62,537 online)
Click here to Skip to main content
Add your own
alternative version


28 bookmarked
Posted 16 May 2007

Sorting with Objects on Multiple Fields

, 21 May 2007
Rate this:
Please Sign up or sign in to vote.
This article shows how to apply sorting on objects


This article demonstrates how to apply sorting on objects. It is useful when you need to apply sorting on objects e.g. Object Person(Name, Age) and you want to apply sorting on Person->Name, or you may wish to apply sorting on multiple fields i.e. Person->name DESC + person->age DESC.

It is very useful when you want to apply multiple column sorting on GridViews with ObjectDataSource.

Using the Code

Using Reflection, its very easy to sort objects. I had used Lists<T> to sort objects and ObjectComparer class is inherited from IComparer<ComparableObject>.

ObjectComparer supports single as well as multiple sorting.

//Created an array of Person object, for which i wish to apply sorting 

Person[] personArray = new Person[] { 
new Person("Ritesh", 26),
new Person("Arpan", 20),
new Person("Arpan", 23),
new Person("Hiren", 22),
new Person("Ankit", 22),
new Person("Dhaval", 23),
new Person("Gaurav", 25)

//Sort array on field Name in Ascending Order
Array.Sort(personArray, new ObjectComparer<Person>("Name"));

//Sort array on field Name Descending and Age Ascending
Array.Sort(personArray, new ObjectComparer<Person>("Name DESC, Age ASC",true));


public class ObjectComparer<ComparableObject> : IComparer<ComparableObject>
    #region Constructor
    public ObjectComparer()

    public ObjectComparer(string p_propertyName)
        //We must have a property name for this comparer to work
        this.PropertyName = p_propertyName;

    public ObjectComparer(string p_propertyName, bool p_MultiColumn)
        //We must have a property name for this comparer to work
        this.PropertyName = p_propertyName;
        this.MultiColumn = p_MultiColumn;

    #region Property
    private bool _MultiColumn;
    public bool MultiColumn
        get { return _MultiColumn; }
        set { _MultiColumn = value; }

    private string _propertyName;
    public string PropertyName
        get { return _propertyName; }
        set { _propertyName = value; }

    #region IComparer<ComparableObject> Members
    /// <summary>
    /// This comparer is used to sort the generic comparer
    /// The constructor sets the PropertyName that is used
    /// by reflection to access that property in the object to 
    /// object compare.
    /// </summary>
    /// <param name="x"></param>
    /// <param name="y"></param>
    /// <returns></returns>
    public int Compare(ComparableObject x, ComparableObject y)
        Type t = x.GetType();
        if (_MultiColumn) // Multi Column Sorting
            string[] sortExpressions = _propertyName.Trim().Split(',');
            for (int i = 0; i < sortExpressions.Length; i++)
                string fieldName, direction = "ASC";
                if (sortExpressions[i].Trim().EndsWith(" DESC"))
                {fieldName = sortExpressions[i].Replace(" DESC", "").Trim();
                direction = "DESC";
                fieldName = sortExpressions[i].Replace(" ASC", "").Trim();

            //Get property by name
            PropertyInfo val = t.GetProperty(fieldName);
            if (val != null)
                //Compare values, using IComparable interface of the property's type
                int iResult = Comparer.DefaultInvariant.Compare
				(val.GetValue(x, null), val.GetValue(y, null));
                if (iResult != 0)
                    //Return if not equal
                    if (direction == "DESC")
                        //Invert order
                        return -iResult;
                        return iResult;
                throw new Exception(fieldName + " is not a valid property to sort on. 
			It doesn't exist in the Class.");
        //Objects have the same sort order
        return 0;
        PropertyInfo val = t.GetProperty(this.PropertyName);
        if (val != null)
            return Comparer.DefaultInvariant.Compare
		(val.GetValue(x, null), val.GetValue(y, null));
            throw new Exception(this.PropertyName + " 
	      is not a valid property to sort on. It doesn't exist in the Class.");



Points of Interest

  • Sorting with objects
  • Multicolumn sorting with objects


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


About the Author

Ritesh Sutaria has about 7+ years of IT experience on various technologies like, PHP, VB, Oracle, PGSql, Sql Server. He has worked on various platforms including Windows, Linux. He has a powerfull problem solving skills which actually makes complex problems into simple problems.

You may also be interested in...

Comments and Discussions

GeneralMy vote of 5 Pin
Dilip Baboo14-Jul-10 9:15
memberDilip Baboo14-Jul-10 9:15 
GeneralOne more simple solution to compare objects. [modified] Pin
neal1233-Jan-10 19:22
memberneal1233-Jan-10 19:22 
GeneralRe: One more simple solution to compare objects. Pin
eddy_r v22-Feb-11 5:44
membereddy_r v22-Feb-11 5:44 
GeneralImproved compare Pin
Gordon Fay15-Nov-07 7:05
memberGordon Fay15-Nov-07 7:05 
QuestionWhat am i doing wrong Pin
abcdefgqwerty11-Jul-07 3:18
memberabcdefgqwerty11-Jul-07 3:18 
AnswerRe: What am i doing wrong Pin
Chazzysb22-Oct-08 0:04
memberChazzysb22-Oct-08 0:04 
GeneralA better way Pin
uncle hammy25-Jun-07 3:26
memberuncle hammy25-Jun-07 3:26 
GeneralGreat ... but there is better ! Pin
Sbastien Ros22-May-07 2:58
memberSbastien Ros22-May-07 2:58 
GeneralRe: Great ... but there is better ! Pin
scosta_FST31-May-07 20:35
memberscosta_FST31-May-07 20:35 
GeneralImprovement Pin
Itay Sagui17-May-07 8:48
memberItay Sagui17-May-07 8:48 
GeneralRe: Improvement Pin
Ritesh Sutaria17-May-07 8:55
memberRitesh Sutaria17-May-07 8:55 

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.170626.1 | Last Updated 22 May 2007
Article Copyright 2007 by Ritesh Sutaria
Everything else Copyright © CodeProject, 1999-2017
Layout: fixed | fluid