Click here to Skip to main content
11,484,640 members (56,628 online)
Click here to Skip to main content

Tagged as

Tips & Tricks: How to Sort a Collection by its Property Name?

, 11 Aug 2010 CPOL 10.4K 5
Rate this:
Please Sign up or sign in to vote.
Sorting a Collection by its Property Name

Several times, we need to sort a collection based on some property name, e.g., we have an Employee collection of type Person. Person consists of EmpId, Name, Age, etc. Now as a user, I need to sort the collection in ascending or descending order either by EmpId, Name or Age. So, how can I do this?

In this post, I will describe a simple technique by which you will easily be able to sort the collection without writing the implementation for each logic. Read the complete article and if you have any suggestions at the end, please don’t forget to share. Feedback is always highly appreciated.

Before going to the actual implementation, let us create our base class, i.e. Employee having some properties like EmpId and Name.

public class Employee
{
    public string Name { get; set; }
    public string EmpId { get; set; }
}

Now, it’s time to create a class which will implement the sorting algorithm. Let us create a class named “FieldSort” and implement the IComparer interface. Let us make it little bit generic. Hence create the class of generic type T and implement it from the generic IComparer interface type of T.

IComparer has a method called Compare(). Just implement it in your class. Now inside the Compare() method, get the PropertyInfo by doing a reflection and get the value of the property of each comparable object as string. Use string.Compare() to compare between the values and return the comparison result as integer.

Here is the full implementation of the class:

using System;
using System.Collections.Generic;
using System.Reflection;

namespace SortLibrary
{
    public class FieldSort<T> : IComparer<T>
    {
        private string propertyName = string.Empty;
        private SortOrder sortOrder = SortOrder.ASC;
        private StringComparison stringComparisonMethod =
                                 StringComparison.CurrentCultureIgnoreCase;

        /// <span class="code-SummaryComment"><summary>
</span>        /// Initializes a new instance of the <span class="code-SummaryComment"><see cref="FieldSort&lt;T&gt;"/> class.
</span>        /// <span class="code-SummaryComment"></summary>
</span>        /// <span class="code-SummaryComment"><param name="propertyName">Name of the property.</param>
</span>        /// <span class="code-SummaryComment"><param name="sortOrder">The sort order.</param>
</span>        /// <span class="code-SummaryComment"><param name="compareMethod">The compare method.</param>
</span>        public FieldSort(string propertyName,
                         SortOrder sortOrder = SortOrder.ASC,
                         StringComparison compareMethod =
                                          StringComparison.CurrentCultureIgnoreCase)
        {
            this.propertyName = propertyName;
            this.sortOrder = sortOrder;
            this.stringComparisonMethod = compareMethod;
        }

        /// <span class="code-SummaryComment"><summary>
</span>        /// Compares the specified x with specified y.
        /// <span class="code-SummaryComment"></summary>
</span>        /// <span class="code-SummaryComment"><param name="x">The original object x.</param>
</span>        /// <span class="code-SummaryComment"><param name="y">The object y which will be compared.</param>
</span>        /// <span class="code-SummaryComment"><returns></returns>
</span>        public int Compare(T x, T y)
        {
            PropertyInfo propertyInfo = x.GetType().GetProperty(propertyName);

            if (propertyInfo != null)
            {
                string xValue = propertyInfo.GetValue(x, null).ToString();
                string yValue = propertyInfo.GetValue(y, null).ToString();

                if (xValue != null && yValue != null)
                {
                    return (sortOrder == SortOrder.ASC)
                            ? string.Compare(xValue, yValue, stringComparisonMethod)
                            : string.Compare(yValue, xValue, stringComparisonMethod);
                }
            }
            return 0;
        }
    }
}

Now let us discuss how to call this sort in our application. If you have the list collection of your Employee information, you need to create the instance of the class FieldSort of type Employee with the proper arguments and pass as a parameter to the method Sort() of the List collection. That’s it. Your collection will sort automatically based on the “propertyName” argument you passed in the FieldSort class instance. You don’t need to call the Compare() method. The IComparer interface will take care of it for you.

Let’s see the calling method:

EmployeeList.Sort(new FieldSort<Employee>("Name",
                                           SortOrder.DESC,
                                           StringComparison.CurrentCultureIgnoreCase));

Once called, you will see the collection sorted according to your algorithm.

Here’s the original collection used for this example:

Once sort is done, you will see the sorted collection (descending order):

So, go ahead and use this class wherever you need. Don’t forget to provide your feedback. They are always welcome.


License

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

Share

About the Author

Kunal Chowdhury (@kunal2383)
Team Leader
India India
Kunal Chowdhury is a Microsoft "Windows Platform Development" MVP (Most Valuable Professional), a Codeproject Mentor, Telerik MVP, Nokia Developer Champion, Speaker in various Microsoft events, Author, passionate Blogger and a Software Engineer by profession.

He is currently working in an MNC located in India. He has a very good skill over XAML, C#, Silverlight, Windows Phone, WPF and Windows Store (WinRT) app development. He posts his findings, articles, tutorials in his technical blog and CodeProject.

Technical Blog: http://www.kunal-chowdhury.com
Facebook: http://facebook.com/blog.kunal
Twitter : http://twitter.com/kunal2383
Follow on   Twitter   Google+   LinkedIn

Comments and Discussions

 
GeneralMy vote of 5 Pin
venugopalm11-Aug-10 10:08
membervenugopalm11-Aug-10 10:08 
GeneralRe: My vote of 5 Pin
KunalChowdhury11-Aug-10 17:42
mentorKunalChowdhury11-Aug-10 17:42 
GeneralMy vote of 5 Pin
Abhishek Sur11-Aug-10 10:04
mvpAbhishek Sur11-Aug-10 10:04 
GeneralRe: My vote of 5 Pin
KunalChowdhury11-Aug-10 17:42
mentorKunalChowdhury11-Aug-10 17:42 

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

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

| Advertise | Privacy | Terms of Use | Mobile
Web03 | 2.8.150520.1 | Last Updated 11 Aug 2010
Article Copyright 2010 by Kunal Chowdhury (@kunal2383)
Everything else Copyright © CodeProject, 1999-2015
Layout: fixed | fluid