Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SortedList/SortedDictionary weird behavior

Can anybody explain why this code:

Dim Data As New SortedList(StringComparer.InvariantCultureIgnoreCase)
Data.Add("AB", 48)
Data.Add("AC", 48)
Data.Add("A-D", 48)
Data.Add("A-", 48)

Generates sorted list with following order:

A-  
AB  
AC  
A-D

Expected (logical and really wanted) order is:

A-
A-D
AB
AC
like image 919
Mike Keskinov Avatar asked Feb 15 '23 00:02

Mike Keskinov


2 Answers

Dim Data As New SortedList(StringComparer.InvariantCultureIgnoreCase)

I think the problem is with the sort rules specified.

Changing InvariantCultureIgnoreCase to Ordinal or OrdinalIgnoreCase solves the problem

Dim Data As New SortedList(StringComparer.OrdinalIgnoreCase)

Here is the Demo

like image 167
Sriram Sakthivel Avatar answered Feb 17 '23 12:02

Sriram Sakthivel


That is how default string comparer is implemented. To customize this you have to implement your own custom IComparer or for better compatibility override Comparer<T> class and pass it to SortedList constructor or pass StringComparer.OrdinalIgnoreCase.

like image 30
Kirill Polishchuk Avatar answered Feb 17 '23 13:02

Kirill Polishchuk