Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does OrderBy work with regard to strings in C#?

Tags:

c#

linq

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?

like image 903
reggaeguitar Avatar asked Mar 27 '14 22:03

reggaeguitar


People also ask

How does the orderby() function work?

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.

What is orderby clause in SQL Server?

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.

What is a string in C?

"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.

Is there a way to sort strings alphabetically?

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:


Video Answer


2 Answers

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)
like image 167
crthompson Avatar answered Oct 21 '22 23:10

crthompson


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

like image 32
Ant P Avatar answered Oct 21 '22 23:10

Ant P