I have a class which has approx 50 properties, instances of this class is added to a list. This list is then added to a Velocity context. Now, I would like to sort this data. Which field, or if it is ascending or descending is not known until the template is being parsed.
Resources I've looked into:
Better way to use Velocity's GenericTools in a Standalone app?
http://velocity.apache.org/tools/devel/generic/
Based on the resources listed here I can't figure out how to solve this. Is the GenericTools available for the Castle's Nvelocity? If not, how may I implement such a generic sort I'm asking for here?
My solution was to write my own sort-class and add this as a context to nvelocity. I'm passing the field to sort on as string and accessing it as reflection. I'm also setting sort ascending or descending by string value. I'm also passing in the name of the comparer and accessing this with reflection as well. I'm then using the List method OrderBy or OrderByDescending with the choosen field and comparer.
I did find parts of the code here: http://zootfroot.blogspot.co.uk/2009/10/dynamic-linq-orderby.html
This is the reflection method for retrieving the field.
Simple comparer example:
Added to Nvelocity context like this:
Accessed from Nvelocity template like this:
Hope it helps someone else...
EDIT: Found an even better way to do it (implements multiple fields sorting): http://www.codeproject.com/Articles/280952/Multiple-Column-Sorting-by-Field-Names-Using-Linq