Sorted Lists

Joined
Feb 22, 2005
Messages
7
Programming Experience
Beginner
Hi
I am trying to arrange my sortedlist so that it will appear in a dropdownbox in the following order:
N
Yes
No
Declined

However it is coming out in alphabetical order according to the key values, how do I change this so that it comes out like above?

code for sorted list below

Dim
DropChoices As New SortedList()
DropChoices.Add("Y", "Yes")
DropChoices.Add("N", "No")
DropChoices.Add("Dec", "Declined")
DropChoices.Add("Def", "N")
 
Your keys are strings and the standard way to sort strings is alphabetically. You need to use the SortedList constructor that takes an IComparer argument and pass it an IComparer that sorts in the way that you want. Better still, since this seems to be an order that you have chosen to suit the situation rather than a systematic order, don't use a SortedList at all. Use a HashTable instead. It is very similar to a SortedList but without the sorting part. You just add items in the order you want.
 
Would this work

VB.NET:
[color=#0000ff]Dim[/color][size=2] DropChoices [/size][size=2][color=#0000ff]As[/color][/size][size=2][color=#0000ff]New[/color][/size][size=2] SortedList()
DropChoices.Add(2, "Yes")
DropChoices.Add(3, "No")
DropChoices.Add(4, "Declined")
DropChoices.Add(1, "N")[/size]
Probably not but try it
 
A SortedList is always sorted using the default IComparer for the Type of its keys, unless you tell it otherwise. This means that strings are sorted alphabetically (and by character unicode order if non-alphanumeric characters are included, I believe) and numbers are sorted in numerically ascending order. If you don't need to use the key values that you had originally, you might as well just use an Array or ArrayList and forget the keys altogether. The idea of a SortedList is that you can add values in any order at any time and still iterate over the list in the order that you expect. If you are just adding a few values in one go and don't need the key:value relationship then a simpler list, like an Array is probably the most suitable.
 
Back
Top