I’ve been writing IComparer’s for a while, and could never figure out a "clean" way to write one which handled mutliple values to compare against.
One time I tried stringing together the multi values, but that was deficient fairly quickly, when you went to datatypes outside of strings.
( If you sort the numbers 1-15 with a string, you get : 1,10,11,12,13,14,15,2,3,4,5,6,7,8,9, which is not what you want). Throw some DateTime’s in the mix, and you see that can get ugly very quickly.
Well, no longer. The following sample shows how to have your cake and eat it too.
The EmployeeComparer can handle strings, times, ints (or others). It can handle 1:N number of sort parameters, where N is probably the overall number of properties you have on your object.
And it only does the work needed, aka, it doesn’t run 5 comparing operations when 1 will suffice.
The little trick is to nest some comparisons, in case there is a "tie" ( compare value of 0 ).
The other good news is that this solution is not limited to 1, 2 or 3 levels of comparing values.
The limit is your imagination.
However, the solution does not do unnecessary compares either.
I think the solution is pretty elegant.
The example can sort ASC or DESC. However, it sorts ASC and DESC for the entire set of SortColumns.
I’m working on my own solution for this. (Just a wrapper object to hold the SortColumn and the direction).
But I will leave that as an exercise for the reader.
Here is the downloadable example. (Right Click and "Save Target As" is your best bet). This is 1.1 code, fyi.