SortedList order broken when keys contain "-"?

G

Guest

Hi,

I think the SortedList does not order itself correctly (or at least
consistently) when its keys contain certain special characters, e.g. the "-"
(hyphen) character. I find this a little hard to believe, so I assume it's
something I don't understand.

Consider the VB.NET console application code below:
-------
Module Module1
Sub Main()

Dim s As New SortedList
s.Add("R", "valR")
s.Add("X", "valX")
s.Add("RA", "valRA")
s.Add("R+", "valR+")
s.Add("R+A", "valR+A")
s.Add("R+B", "valR+B")
s.Add("RB", "valRB")
s.Add("R+X", "valR+X")
s.Add("RX", "valRY")

For i As Integer = 0 To s.Count - 1
Console.WriteLine(s.GetKey(i))
Next
Console.ReadLine()

End Sub
------------

Running this will produce output in (what I think is) the correct order.
That is, the value "R" comes first, then all of the keys with values starting
with "R+" come next, then all strings with other characters following the "R"
come next in alphabetical order. The order I get is:

R
R+
R+A
R+B
R+X
RA
RB
RX
X

Which I think is correct. Now, if I simply replace all the "+" characters
in the code above with a "-", the collection is no longer in that same order.
Instead I get:

R
R-
RA
R-A
RB
R-B
RX
R-X
X

It seems that this behavior occurs only with the "-"; I've tried several
other special characters and they seem to give the correct results.

But, if I replace with a "~", which I thought sorts after alphabetic
characters, I get an order like using the "+" character; that is, all the
"R~" strings come before the other R strings. I think a string starting with
"R~" should sort after "RA", at least according to the character map.

I get the same results if I create the sorted list using
CaseInsensitveComparer in the constructor.

What don't I understand?

Thanks for any insight anyone can give.
 
F

Filipe Marcelino

Hi,

I'm not sure but I think that's an errorbecause, maybe the algorithm of
sort is confusing the char '-' (ascii value = 45) and char '-' (196)
witch, graphicaly it's the same...

Regards,
Filipe Marcelino
 
W

William Stacey [MVP]

I think if you use StringComparer.OrdinalIgnoreCase like below, you should
get the results you expect:

SortedList<string, string> s = new SortedList<string,
string>(StringComparer.OrdinalIgnoreCase);
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top