Johannes Hansen has a nice article on dynamic list sorting with Generics with source code
From his article:
So how do you use this comparer? Well, itâ€™s as easy as 1-2-3:S//Example
string orderBy = "FirstName, LastName DESC"; // 1
DynamicComparer<Person> comparer = new DynamicComparer<Person>(orderBy); // 2
persons.Sort(comparer.Compare); // 3
- Declare a sort string or a
SortPropertyarray. Note: This could be created and maintained by a custom editgrid.
- Declare an instance of the
DynamicComparerclass using the generic constructor.
- Call the sort method on the
So whatâ€™s going on behind the scenes? Letâ€™s begin at line 2 of the previous example. At the time of instantiation of the
DynamicComparer, the class will first parse the input string into a
SortPropertieswill then be validated against the type we specified when instantiating the
DynamicComparer, in this case, â€œ
Personâ€. This validation checks if the
public, if it has any public properties named â€œ
FirstNameâ€ and â€œ
LastNameâ€, if these properties are readable, and finally, if these properties are of a type that implements the
IComparableinterface. If any of these validations fail, the class will throw an exception. If the validation succeeds, the class will then generate a dynamic method using the specified
SortPropertyiesand instantiate an internal delegate pointing to the method. The â€œ
Compareâ€ method on the
DynamicComparerwill then in turn be able to invoke this delegate when called. This means that the comparer is ready for use.
Note: If you want to change the sorting of an instance of the
DynamicComparer, you can call the â€œ
Initializeâ€ method on the instance and pass in a new
ORDER BYstring or a
At the next step, we call the â€œ
Sortâ€ method on the â€œpersonsâ€ list passing in a reference to the
Very slick! Again, his source code is in the article, I suggest checking out the performance gains.