Consider this code
var strings2 = new List<string>
{
"0", // Ascii code 48 (decimal)
"|" // Ascii code 125 (decimal)
};
var sorted = strings2.OrderBy(x => x).ToArray();
Sorted contains "|", "0"
. Now consider this code (all I did was change "|"
to "."
)
var strings2 = new List<string>
{
"0", // Ascii code 48 (decimal)
"." // Ascii code 46 (decimal)
};
var sorted = strings2.OrderBy(x => x).ToArray();
Now sorted contains ".", "0"
In both cases the "0"
comes at the end even though 125 > 48, what is going on here?
The ".OrderBy" function utilizes the default comparer for a string. That comparer is not necessarily going to return a sort order based on the ASCII code. For a list of all the different string comparers, see the article on MSDN.
orderby clause (C# Reference) In a query expression, the orderby clause causes the returned sequence or subsequence (group) to be sorted in either ascending or descending order. Multiple keys can be specified in order to perform one or more secondary sort operations. The sorting is performed by the default comparer for the type of the element.
"c string tutorial". Here, c string tutorial is a string. When compiler encounter strings, it appends a null character \0 at the end of the string. Before we can actually work with strings, we need to declare them first. Strings are declared in a similar wayas arrays. Only difference is that, strings are of char type.
The current culture is used by default, which has a sorting order intended to sort strings 'alphabetically' rather in strictly lexical order, for some definition of alphabetically. It sounds like what you want is the comparison to not use culture-specific rules. Have you tried StringComparison.Ordinal:
The order depends on the culture that you use.
You can pass the culture in an overload to OrderBy.
var sorted = strings2.OrderBy(x => x, StringComparer.InvariantCulture)
Here you go:
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.
Source: String.Compare Method on MSDN
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