LINQ OrderBy igorning with true ASCII order

I am trying to sort strings ("A", "_", "a") using LINQ in C # in ASCII order, ignoring case sensitivity. According to the ASCII table , the lines I'm interested in are:

  • A = 65
  • _ = 95
  • a = 97

So I expect the result to be

A, _, a

However, I tried all the variations of StringComparer, none of them gave me the desired result. Below is my test program and output:

    string[] words = { "A", "_", "a" };

    var sortedWords = words.OrderBy(a => a, StringComparer.OrdinalIgnoreCase);
    Console.WriteLine("OrdinalIgnoreCase: " + string.Join(", ", sortedWords));

    sortedWords = words.OrderBy(a => a, StringComparer.CurrentCultureIgnoreCase);
    Console.WriteLine("CurrentCultureIgnoreCase: " + string.Join(", ", sortedWords));

    sortedWords = words.OrderBy(a => a, StringComparer.InvariantCultureIgnoreCase);
    Console.WriteLine("InvariantCultureIgnoreCase: " + string.Join(", ", sortedWords));

      

output:

OrdinalIgnoreCase: A, a, _

CurrentCultureIgnoreCase: _, A, a

InvariantCultureIgnoreCase: _, A, a

.NET fiddle here.

How do I sort the array to get "A, _, a" according to ASCII order?

+3


source to share


1 answer


Use StringComparer.Ordinal

.... By using StringComparer.OrdinalIgnoreCase

, you are ignoring this case, so it will probably silently convert everything to uppercase.

From MSDN:

OrdinalIgnoreCase :

The StringComparer returned by the OrdinalIgnoreCase property treats the characters in the strings for comparison as if they were converted to uppercase using the conventions of an invariant culture, and then performs a simple byte comparison that is language independent.



and

Ordinal :

The StringComparer returned by the Ordinal property does a simple byte comparison that is language independent.

The sample is formatted correctly: http://ideone.com/0YTUdr

+6


source







All Articles