System.Collections.SortedList and sorting
Posted: (EET/GMT+2)
I was writing a Delphi .NET application today where I need to sort strings. Of course, my favorite for simple situations is the System.Collections.SortedList class, and this is what I also used today.
With it's easy operation, I'm able to sort strings and also associate data with the keys. But, today I noticed that the default sorting for strings assumes that the letters V and W are the same. However, this is not the case in Finland -- those letters are and should be different.
According to the Framework documentation, the SortedList class uses by default "the IComparable implementation provided by the keys themselves", which in my case means System.String.
Now, being aware of .NET's support for cultures, I thought that maybe the default for sorting was something like the U.S. based sorting (as often happens), but indeed it was not. Instead, the System.Threading.Thread.CurrentCulture.Name member returns the correct culture for this northern land: "fi-FI".
Having limited time to solve this puzzle, I decided to go the easy way, and specify another IComparable implementation to the constructor of the SortedList class. So, my tip for today follows.
To get things working the Finnish way (i.e. V and W being different), I just constructed the object like this:
procedure PageGen.GetList();
Var
List : System.Collections.SortedList;
begin
List := System.Collections.SortedList.Create(
System.Collections.CaseInsensitiveComparer.DefaultInvariant);
...
As you can see the DefaultInvariant static property of the System.Collections.CaseInsensitiveComparer class is the key here.