Click here to Skip to main content
Click here to Skip to main content

Sorting Collection of Custom Types Generically

, 28 Jul 2007 CPOL
Rate this:
Please Sign up or sign in to vote.
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

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

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

Share

About the Author

Kiran Bheemarti
Web Developer
United States United States
No Biography provided

Comments and Discussions

 
GeneralIn C# 2 I usually use an anonymous delegate that matches Comparision&lt;T&gt; Pinmembernmajor30-Jul-07 23:33 
GeneralRe: In C# 2 I usually use an anonymous delegate that matches Comparision&lt;T&gt; PinmemberJohannes Hansen31-Jul-07 21:11 
GeneralRe: In C# 2 I usually use an anonymous delegate that matches Comparision&lt;T&gt; Pinmemberbakirankumar4-Aug-07 13:54 
GeneralRe: In C# 2 I usually use an anonymous delegate that matches Comparision&lt;T&gt; Pinmembernmajor5-Aug-07 21:30 
GeneralPerformance PinmemberJohannes Hansen30-Jul-07 19:45 
GeneralRe: Performance Pinmemberbakirankumar4-Aug-07 14:35 
GeneralSuggestion.... PinmemberJames Curran30-Jul-07 6:43 
GeneralRe: Suggestion.... Pinmemberbakirankumar30-Jul-07 7:15 
GeneralIComparable PinmemberSeishin#29-Jul-07 2:28 
AnswerRe: IComparable Pinmemberchsunil29-Jul-07 8:54 

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
Web02 | 2.8.1411023.1 | Last Updated 28 Jul 2007
Article Copyright 2007 by Kiran Bheemarti
Everything else Copyright © CodeProject, 1999-2014
Layout: fixed | fluid