I'm trying to sort strings ("A", "_", "a") using LINQ in C# in ASCII order while ignoring case sensitivity. According to the ASCII table, the strings I'm interested are:
So I would expect the output to be
A, _, a
However I tried all the StringComparer variations, none of them give me the desired output. The following 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 the ASCII ordering?
OrderBy (x => x.Name); I was surprised to see that the default comparer used by OrderBy , when applied to strings, is case insensitive: given a , B , c the code produces a , B , c as the sorted result.
The OrderBy() Method, first sort the elements of the sequence or collection in ascending order after that ThenBy() method is used to again sort the result of OrderBy() method in ascending order.
In LINQ, the OrderBy operator is used to sort the list/ collection values in ascending order. In LINQ, if we use order by the operator by default, it will sort the list of values in ascending order.
If you want to rearrange or sort the elements of the given sequence or collection in descending order in query syntax, then use descending keyword as shown in below example. And in method syntax, use OrderByDescending () method to sort the elements of the given sequence or collection.
Use StringComparer.Ordinal
.... By using StringComparer.OrdinalIgnoreCase
you are ignoring the case, so probably it is silently converting everything to uppercase.
From MSDN:
OrdinalIgnoreCase:
The StringComparer returned by the OrdinalIgnoreCase property treats the characters in the strings to compare as if they were converted to uppercase using the conventions of the invariant culture, and then performs a simple byte comparison that is independent of language.
and
Ordinal:
The StringComparer returned by the Ordinal property performs a simple byte comparison that is independent of language.
Sample correctly formatted: http://ideone.com/0YTUdr
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With