| Sloan 的个人资料Granada Coder, C#, Sql S...照片日志列表 | 帮助 |
|
2006/6/19 Advanced IComparer // Sorting on Multiple ValuesI'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. 评论 (12)
引用通告此日志的引用通告 URL 是: http://sholliday.spaces.live.com/blog/cns!A68482B9628A842A!141.trak 引用此项的网络日志
|
|
|