views:

141

answers:

3

Hello everyone,

I'm using a SortedDictonary(Of String, String) in my application, and I experience a strange sorting behavior. Consider the following code example:

Dim Dic As New SortedDictionary(Of String, String)
Dic.Add("'A", "")
Dic.Add("A", "")
Dic.Add("'B", "")
Dic.Add("B", "")
Dic.Add("'C", "")
Dic.Add("C", "")

I would expect the keys to be sorted as "'A", "'B", "'C", "A", "B", "C", which is what you get when comparing the keys "by hand", through the < operator. And yet, iterating through the keys returns "A", "'A", "B", "'B", "C", "'C".

How can I change the SortedDictionary behavior to sort the words beginning with ' first?

Thank you, CFP

A: 

Every key in a SortedDictionary(TKey, TValue) must be unique according to the default comparer.

SortedDictionary(TKey, TValue) requires a comparer implementation to perform key comparisons. This constructor uses the default (local culture dependent) generic equality comparer Comparer(T).Default. If type TKey implements the System.IComparable(T) generic interface, the default comparer uses that implementation. Alternatively, you can specify an implementation of the IComparer(T) generic interface by using a constructor that accepts a comparer parameter.

Dim Dic As New SortedDictionary(Of String, String)(StringComparer.Ordinal)
Dic.Add("'A", "")
Dic.Add("A", "")
Dic.Add("'B", "")
Dic.Add("B", "")
Dic.Add("'C", "")
Dic.Add("C", "")


For Each Item As KeyValuePair(Of String, String) In Dic
  Console.WriteLine(Item.Key & " > " & Item.Value)
Next

Output:

'A > 
'B > 
'C > 
A > 
B > 
C > 
serhio
A: 

You need to specify a different comparer:

Dim Dic As New SortedDictionary(Of String, String)(StringComparer.Ordinal)
Darin Dimitrov
+3  A: 

In my phone book, John O'Leary sorts between Ole Tractors and Dennis Oleck. You'll have to use a non-culture dependent sort:

Dim Dic As New SortedDictionary(Of String, String)(StringComparer.Ordinal)
Hans Passant
Indeed, I didn't think of this. Thanks a lot!
CFP