Click here to Skip to main content
13,668,689 members
Click here to Skip to main content
Add your own
alternative version


12 bookmarked
Posted 28 Jul 2007
Licenced CPOL

Sorting Collection of Custom Types Generically

, 28 Jul 2007
Rate this:
Please Sign up or sign in to vote.
Sorting a collection of custom types


With the addition of Generic collections in .NET 2.0 life became easy, after using the Collections in System.Collections.Generic namespace, we almost forget how life used to be before these collections got added. It's hard to imagine adding, retrieving, finding, sorting, etc. Functionalities on Collection of objects say when you use ArrayList and other non-generic collections.

In this article, I am dealing with sorting functionality of List<T> Collection class.

Sample Code

List<string> collOfStrings = new List<String>; 

As you see, it's easy to sort a List<T> collection provided you are dealing with basic types like strings, integers etc., since they implement IComparable and Framework knows how to compare two basic types.
It gets a little tricky when you add custom entities, "entities" that represent your business objects, we must provide the functionality to compare these entities in order for the sort to work, this can be done in two ways:

  1. Make your Custom entities implement IComparable and provide comparison logic
  2. Create a generic Comparison type and pass an instance of this guy to the sort method.

This article deals with the 2nd choice.

I implemented the generic IComparer to give a generic way of comparing two custom entities.

Using the Code

entities.Sort(new CompareEntities<Entity>
	(Direction.Ascending, typeof(Entity).GetProperties()[2].Name));

Complete Code

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

namespace Sort
    class Program
        public enum Direction
            Ascending = 0,
            Descending = 1,

        static void Main(string[] args)
            List<Entity> entities = new List<Entity>();
            entities.Add(new Entity("tommy", 10, 99));
            entities.Add(new Entity("Dicky", 12, 100));
            entities.Add(new Entity("Harry", 11, 90));
            List<string> collString = new List<string>();

            Console.WriteLine("------------------------sorting using .NET 
		supplied List Sort----------------------------------------------");
            //entities.Sort(); will not work, type entity should implement IComparable 
	   //and give logic regarding comparison of two entity types
            collString.Sort(); //Works fine for basic types implement IComparable.

            Console.WriteLine("------------------------sort on " + 
		typeof(Entity).GetProperties()[2].Name + 
		" ascending ----------------------------------");
            entities.Sort(new CompareEntities<Entity>
		(Direction.Ascending, typeof(Entity).GetProperties()[2].Name));


            Console.WriteLine("-------------------------sort on " + 
		typeof(Entity).GetProperties()[1].Name + 
		" ascending----------------------------------");
            entities.Sort(new CompareEntities<Entity>
		(Direction.Ascending, typeof(Entity).GetProperties()[1].Name));


            Console.WriteLine("--------------------------sort on " + 
		typeof(Entity).GetProperties()[4].Name + 
		" Descending---------------------------------");
            entities.Sort(new CompareEntities<Entity>
		(Direction.Descending, typeof(Entity).GetProperties()[4].Name));


            Console.WriteLine("--------------------------sort on field 3 
            entities.Sort(new CompareEntitiesByPropertyIndex<Entity>
		(Direction.Ascending, 3));


            Console.WriteLine("Press any key......");


        public static void PrintEntities(List<Entity> entities)
            foreach (Entity entity in entities)
                Console.WriteLine(String.Format("Name : {0} RollNumber : 
				{1} Total : {2} CreatedOn : {3}", 
                    entity.Name, entity.RollNumber.ToString(), 
			entity.Total.ToString(), entity.CreatedOn.ToString()));

        public class CompareEntities<T> : IComparer<T>
            private Direction _sortDirection;
            public Direction SortDirection
                get { return _sortDirection; }
                set { _sortDirection = value; }

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

            public CompareEntities(
                Direction dir, string fieldName)
                SortDirection = dir;
                PropertyName = fieldName;

            #region IComparer<T> Members

            public int Compare(T x, T y)
                if (typeof(T).GetProperty(PropertyName) == null)
                    throw new Exception(String.Format
		   ("Given property is not part of the type {0}", PropertyName));

                object objX = typeof(T).GetProperty(PropertyName).GetValue(x, null);
                object objY = typeof(T).GetProperty(PropertyName).GetValue(y, null);

                int retVal = default(int);
                retVal = ((IComparable)objX).CompareTo((IComparable)objY);

                return retVal;


        public class CompareEntitiesByPropertyIndex<T> : IComparer<T>
            CompareEntities<T> _comparer = null;
            public CompareEntitiesByPropertyIndex(
                Direction dir, int index)
                _comparer = new CompareEntities<T>(dir, 

            #region IComparer<T> Members
            public int Compare(T x, T y)
                return _comparer.Compare(x, y);

        public class BaseEntity
            private DateTime _createdOn;
            public DateTime CreatedOn
                get { return _createdOn; }
                set { _createdOn = value; }

            private DateTime _updatedOn;
            public DateTime UpdatedOn
                get { return _updatedOn; }
                set { _updatedOn = value; }

        public class Entity : BaseEntity 
            private string _name;
            public string Name
                get { return _name; }
                set { _name = value; }

            private int _rollNumber;
            public int RollNumber
                get { return _rollNumber; }
                set { _rollNumber = value; }

            private double _total;
            public double Total
                get { return _total; }
                set { _total = value; }

            public Entity(string name, int rollNo, double tot)
                Name = name;
                RollNumber = rollNo;
                Total = tot;
                CreatedOn = DateTime.Now.AddDays(-1);
                UpdatedOn = DateTime.Now.AddDays(1);


  • 28th July, 2007: Initial post


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


About the Author

Kiran Bheemarti
Web Developer
United States United States
No Biography provided

You may also be interested in...


Comments and Discussions

GeneralIn C# 2 I usually use an anonymous delegate that matches Comparision&lt;T&gt; Pin
nmajor30-Jul-07 22:33
membernmajor30-Jul-07 22:33 
GeneralRe: In C# 2 I usually use an anonymous delegate that matches Comparision&lt;T&gt; Pin
Johannes Hansen31-Jul-07 20:11
memberJohannes Hansen31-Jul-07 20:11 
GeneralRe: In C# 2 I usually use an anonymous delegate that matches Comparision&lt;T&gt; Pin
bakirankumar4-Aug-07 12:54
memberbakirankumar4-Aug-07 12:54 
GeneralRe: In C# 2 I usually use an anonymous delegate that matches Comparision&lt;T&gt; Pin
nmajor5-Aug-07 20:30
membernmajor5-Aug-07 20:30 
GeneralPerformance Pin
Johannes Hansen30-Jul-07 18:45
memberJohannes Hansen30-Jul-07 18:45 
GeneralRe: Performance Pin
bakirankumar4-Aug-07 13:35
memberbakirankumar4-Aug-07 13:35 
GeneralSuggestion.... Pin
James Curran30-Jul-07 5:43
memberJames Curran30-Jul-07 5:43 
GeneralRe: Suggestion.... Pin
bakirankumar30-Jul-07 6:15
memberbakirankumar30-Jul-07 6:15 
GeneralIComparable Pin
Seishin#29-Jul-07 1:28
memberSeishin#29-Jul-07 1:28 
AnswerRe: IComparable Pin
chsunil29-Jul-07 7:54
memberchsunil29-Jul-07 7:54 

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 | Cookies | Terms of Use | Mobile
Web04-2016 | 2.8.180820.1 | Last Updated 28 Jul 2007
Article Copyright 2007 by Kiran Bheemarti
Everything else Copyright © CodeProject, 1999-2018
Layout: fixed | fluid