Didn't I tell you that I love .Net 2.0? If I didn't I am saying it now...
This is new a method in .NET 2.0, but who plays with it should know it by now. Instead of working hard trying to sort a collection (or a list which is a descendant of it) of some entities, now you have the Sort method, which does it for FREE and in better performence.
Any case I decided to show a simple example to whom that doesn't know it or just want to be impressed again from it.
* Comment: I assumes in this post that you are familier with Generics and delegates.
Let's assume that you have an entity structured like:
public struct Entity
{
private int _id;
private string _name;
// and more...
public int Id
{
get{return _id;}
set{_id = value;}
}
public string Name
{
get{return _name;}
set{_name = value;}
}
}
Now, suppose you have a list of these entities and you want to sort it by their name and display it sorted. Follow the example code below and see how it easy using anonymous delegate:
//sortDirecion is a global variable that determines the sort direction
int sortParam = sortDirection == "Ascending" ? 1 : -1;
entitiesList.Sort(new Comparison<Entity>(
delegate(Entity e1, Entity e2)
{
return sortParam * e1.Name.CompareTo(e2.Name);
})
};
Nice & easy that's it (with no sofisticated actions).
Some more tutorials about anonymous delegates (or delegates in general) you can find in Oren Elenbogen's (a team leader in my department) blog here.
So, be well.
p.s. Again... I will be glad to head some comment or sharpening.