Why does CompareTo not sort my string using ASCII code ordering?

Duš*_*ský 6 c# string

In C# "123-delete.json".CompareTo("123.json") evaluates to 1, meaning "123-delete.json" is to be sorted after "123.json".

This is unexpected for me, as according to the ASCII table . comes after -.

在此处输入图片说明

I tried to browse the CompareTo implementation on GitHub, but it seems this logic is implemented in a native function (InternalCompareString).

Why does the CompareTo method not follow the ASCII ordering?

Also, is there a way to view the source code for native functions such as InternalCompareString?

Ack*_*ari 4

使用

string.Compare("123-delete.json", "123.json", StringComparison.Ordinal)
Run Code Online (Sandbox Code Playgroud)

或者

string.CompareOrdinal("123-delete.json", "123.json")
Run Code Online (Sandbox Code Playgroud)

或者

StringComparer.Ordinal.Compare("123-delete.json", "123.json")
Run Code Online (Sandbox Code Playgroud)

在 C# 中,字符串的比较默认取决于区域性,并StringComparison.Ordinal让函数根据二进制排序规则来压缩字符串。

正如 @JeppeStigNielsen 提到的,返回的对象StringComparer.Ordinal实现了该IComparer<string>接口,这使您可以在拥有SortedSet<string>SortedList<string>或任何类型的使用比较对象的字符串“集”的情况下使用这种排序顺序。