Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

C# string sorting doesn't work as expected. What's the problem?

given an array of strings, and I want to sort it, the code as follows

string[] s = ["=:rr", "2:yy", "=:hh"];
Array.Sort(s);
foreach (var item in s)
{
    Console.WriteLine(item);
}

my expected result:

2:yy
=:hh
=:rr

the actual result:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

=:hh
=:rr
2:yy

From what I understand, strings are sorted based on the Unicode value of each character. ‘2’ has a Unicode value of 50, and ‘=’ has a Unicode value of 61. So why isn’t the result as expected?

>Solution :

From what I understand, strings are sorted based on the Unicode value of each character.

Not by default, from Collation, sorting, and string comparison

Each language has a set or sets of rules for how language strings should be sorted or "collated" into an ordered list. Collation is the term for how the sorting order of strings of characters is determined. This concept is important to globalization when it comes to the alphabetic order of each language.

By default a culture sensitive comparer will be used. If you want a byte comparison , see StringComparer.Ordinal

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading