Yesup
 
 

Yamabay Knowledge Base

 

How to sort SortedList in Numerical Way

Previous Article Back to TOC Next Article

SortedList is a convenient class which allows the Program to be able to sort ArrayList or Hashtable easily. But the problem is, the default sort is String Ascending Sort. If you want to do numerical sort, then the default sort method will convert all the numbers into string before sorting. The result will not be as requited, because the number 11 will be small than the number 2, since string 11 is small then string 2.


To solve this problem, the Class SortedList constructor allow a 2nd parameter, which passes an new instance of IComparer to this SortedList. ONce passed, the SortedList will use this specific SOrt method, instead of the default sort method to sort.


To implement IComparer, you will need to have a class like MyComparerClass: IComparer, and then implement a method called Compare(object x, object y) . This compare will return -1 if x < y; 0 if x = y, and 1 if x > y.


The Constructor of the SortedList will be like:


ArrayList list = new ArrayList();


list.add(key, data);


:


SortedList sl = new SortedList(list, new MyComparerClass());


For details, please refer to: http://support.microsoft.com/?id=320727

Yesup
Top Stories Travel Movies Gift Ideas Free Software Games