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:
- Make your Custom entities implement
IComparable
and provide comparison logic - 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();
collString.Sort();
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
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.