vendredi 20 février 2015

Easiest method to OrderBy a String using StringComparison.Ordinal

I've found a bug (in my code) that results from String.CompareTo and binary search because my custom IComparer (for the wrapping type) uses String.Compare(x, y, StringComparison.Ordinal).


This is because items.OrderBy(i => i.Name) (where Name is of type string) used to build the Array to search used the string object itself as the IComparable - and such has different rules:



The comparison uses the current culture to obtain culture-specific information such as casing rules and the alphabetic order of individual characters. For example, a culture could specify that certain combinations of characters be treated as a single character, or uppercase and lowercase characters be compared in a particular way, or that the sorting order of a character depends on the characters that precede or follow it.



For example, {A, b, C} is sorted as [A, b, C] with the OrderBy but should be [b, A, C] per the Ordinal comparison - since it is not the binary search is failing.


Now, with the "context" out of the way,


What is the easiest (eg. without implementing a custom IComparer for strings) way to order the strings the same as with String.Compare(.., StringComparison.Ordinal)?


Aucun commentaire:

Enregistrer un commentaire