Click here to Skip to main content
15,867,686 members
Articles / Programming Languages / C#
Article

Sorting Collection of Custom Types Generically

Rate me:
Please Sign up or sign in to vote.
2.91/5 (10 votes)
28 Jul 2007CPOL1 min read 34.4K   136   12   10
Sorting a collection of custom types

Introduction

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

C#
List<string> collOfStrings = new List<String>; 
collOfString.Add("string1")
collOfString.Add("string2")
collOfString.Sort()

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

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

Complete Code

C#
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>();
            collString.Add("tommy");
            collString.Add("Dicky");
            collString.Add("Harry");

            Console.WriteLine("------------------------sorting using .NET 
		supplied List Sort----------------------------------------------");
            Console.WriteLine();
            //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 ----------------------------------");
            Console.WriteLine();
            entities.Sort(new CompareEntities<Entity>
		(Direction.Ascending, typeof(Entity).GetProperties()[2].Name));

            PrintEntities(entities);

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

            PrintEntities(entities);

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

            PrintEntities(entities);

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

            PrintEntities(entities);

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

            Console.Read();
        }

        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;
            }

            #endregion
        }

        public class CompareEntitiesByPropertyIndex<T> : IComparer<T>
        {
            CompareEntities<T> _comparer = null;
            public CompareEntitiesByPropertyIndex(
                Direction dir, int index)
            {
                _comparer = new CompareEntities<T>(dir, 
                    typeof(T).GetProperties()[index].Name);
            }

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

        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);
            }
        }
    }
}

History

  • 28th July, 2007: Initial post

License

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


Written By
Web Developer
United States United States
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
GeneralIn C# 2 I usually use an anonymous delegate that matches Comparision&lt;T&gt; Pin
nmajor30-Jul-07 22:33
nmajor30-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
Johannes Hansen31-Jul-07 20:11 
GeneralRe: In C# 2 I usually use an anonymous delegate that matches Comparision&lt;T&gt; Pin
Kiran Bheemarti4-Aug-07 12:54
Kiran Bheemarti4-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
nmajor5-Aug-07 20:30 
GeneralPerformance Pin
Johannes Hansen30-Jul-07 18:45
Johannes Hansen30-Jul-07 18:45 
GeneralRe: Performance Pin
Kiran Bheemarti4-Aug-07 13:35
Kiran Bheemarti4-Aug-07 13:35 
GeneralSuggestion.... Pin
James Curran30-Jul-07 5:43
James Curran30-Jul-07 5:43 
GeneralRe: Suggestion.... Pin
Kiran Bheemarti30-Jul-07 6:15
Kiran Bheemarti30-Jul-07 6:15 
GeneralIComparable Pin
Seishin#29-Jul-07 1:28
Seishin#29-Jul-07 1:28 
AnswerRe: IComparable Pin
chsunil29-Jul-07 7:54
chsunil29-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.