Geeks With Blogs
Joel Ross

Dave Donaldson prodded me this morning to get off my butt and post an update to my previous multi-sorting comparer, and I'm going to do that now. Man, Dave, get off my back!

Ok. He didn't prod. He asked if I'd updated it to support Generics, which I had. If you look at the previous one, not a lot has changed, so let's just highlight the changes. First, instead of using an ArrayList to store the internal sorting classes, I'm using a Generics (it really wouldn't be a good upgrade if I didn't use generics in my implementation, would it?), and instead of using objects in the comparison class, it can now be typed, which means better compile time checks. This changes both the Compare method, and the CheckSort method (CheckSort is what Compare calls to perform the recursive sorting, which is what allows you to sort and subsort your collections). Here's the updated code:

   1:  public int Compare(T x, T y) {
   2:      if(SortClasses.Count == 0) {
   3:          return 0;
   4:      }
   5:      return CheckSort(0, x, y);
   6:  }
   8:  private int CheckSort(int SortLevel, T MyObject1, T MyObject2) {
   9:      int returnVal = 0;
  11:      if(SortClasses.Count - 1 >= SortLevel) {
  12:          object valueOf1 = MyObject1.GetType().GetProperty(SortClasses[SortLevel].SortColumn).GetValue(MyObject1, null);
  13:          object valueOf2 = MyObject2.GetType().GetProperty(SortClasses[SortLevel].SortColumn).GetValue(MyObject2, null);
  15:          if(SortClasses[SortLevel].SortDirection == SortDirection.Ascending) {
  16:              returnVal = ((IComparable) valueOf1).CompareTo(valueOf2);
  17:          } 
  18:          else {
  19:              returnVal = ((IComparable) valueOf2).CompareTo(valueOf1);
  20:          }
  22:          if(returnVal == 0){
  23:              returnVal = CheckSort(SortLevel + 1, MyObject1, MyObject2);
  24:          }
  25:      }
  26:      return returnVal;
  27:  }

So now, you can sort your generic collections easily and flexibly. This could be used in conjunction with an ObjectDataSource pretty easily, and I may post an example of that at a later date.

The full code snippet is on CodeKeep and is available here.

While I'm on the subject of CodeKeep, Dave added a new feature where you can link to your Code snippets using a nice little icon. Here's my code snippets - there's only five right now, but I plan to add more in the near future (once I get some time!):

Technorati Tags: | |

Posted on Wednesday, April 12, 2006 4:59 PM | Back to top

Comments on this post: Multiple Property Sorting Of Generic Collections

No comments posted yet.
Your comment:
 (will show your gravatar)

Copyright © Joel Ross | Powered by: