A coworker of mine recently pointed me to a blogpost by Marc Brooks which contains a fantastic library for sorting objects. The objects don't have to implement an interface or inherit from a base class, it pretty much works with whatever you throw at it. And it's very fast.
Suppose you have the following class:
public class MyClass
{
private int _intValue;
private double _doubleValue;
private string _stringValue;
private decimal _decimalValue;
private DateTime _dateTimeValue;
public int IntValue
{
get { return _intValue; }
set { _intValue = value; }
}
public double DoubleValue
{
get { return _doubleValue; }
set { _doubleValue = value; }
}
public string StringValue
{
get { return _stringValue; }
set { _stringValue = value; }
}
public decimal DecimalValue
{
get { return _decimalValue; }
set { _decimalValue = value; }
}
public DateTime DateTimeValue
{
get { return _dateTimeValue; }
set { _dateTimeValue = value; }
}
}
And suppose we have a method which creates a big list filled with instances of this class for us:
private static List<MyClass> CreateBigList()
{
List<MyClass> list = new List<MyClass>();
for (int a = 0; a < 10; a++)
{
for (int b = 0; b < 10; b++)
{
for (int c = 0; c < 10; c++)
{
for (int d = 0; d < 10; d++)
{
for (int e = 0; e < 10; e++)
{
MyClass myObject = new MyClass();
myObject.IntValue = a;
myObject.DoubleValue = b;
myObject.StringValue = "string" + c;
myObject.DecimalValue = d;
myObject.DateTimeValue = DateTime.Now.AddSeconds(e);
list.Add(myObject);
}
}
}
}
}
return list;
}
The list will contain 100,000 instances, ordered ascending.
Using Marc Brooks' DynamicComparer, it's incredibly easy to sort this list differently:
static void Main(string[] args)
{
List<MyClass> list = CreateBigList();
string sortExpression = "IntValue DESC, DoubleValue DESC, "
+ "StringValue DESC, DecimalValue DESC, DateTimeValue DESC";
DynamicComparer<MyClass> dynamicComparer =
new DynamicComparer<MyClass>(sortExpression);
DateTime before = DateTime.Now;
list.Sort(dynamicComparer.Comparer);
DateTime after = DateTime.Now;
Console.WriteLine("Elapsed Time: " + after.Subtract(before));
Console.ReadLine();
}
Based on the sortExpression, the list will now be sorted in the reversed order. On my computer, the output of this code was:
Elapsed Time: 00:00:00.5908496
I'd say that's pretty fast for sorting 100,000 instances on 5 properties. And incredibly easy.