c# - 排序的特殊性

标签 c# .net

字符代码'-'是45,字符代码'a'是 97。很明显 '-' < 'a'是真的。

Console.WriteLine((int)'-' + " " + (int)'a');
Console.WriteLine('-' < 'a');

45 97
True

因此下面排序的结果是正确的

var a1 = new string[] { "a", "-" };
Console.WriteLine(string.Join(" ", a1));
Array.Sort(a1);
Console.WriteLine(string.Join(" ", a1));

a -
- a

但是为什么下面排序的结果是错误的呢?

var a2 = new string[] { "ab", "-b" };
Console.WriteLine(string.Join(" ", a2));
Array.Sort(a2);
Console.WriteLine(string.Join(" ", a2));

ab -b
ab -b

最佳答案

- 被忽略,

so - = "" < a
and -b = "b" > "ab"

这是因为文化排序(默认)

https://msdn.microsoft.com/en-us/library/system.globalization.compareoptions(v=vs.110).aspx

The .NET Framework uses three distinct ways of sorting: word sort, string  

sort, and ordinal sort. Word sort performs a culture-sensitive comparison of strings. Certain nonalphanumeric characters might have special weights assigned to them. For example, the hyphen ("-") might have a very small weight assigned to it so that "coop" and "co-op" appear next to each other in a sorted list. String sort is similar to word sort, except that there are no special cases. Therefore, all nonalphanumeric symbols come before all alphanumeric characters. Ordinal sort compares strings based on the Unicode values of each element of the string.

关于c# - 排序的特殊性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39653066/

相关文章:

C# 迁移到 Java,只需要知道一些事情

c# - 使用 CaptureElement/MediaCapture 时如何在网络摄像头之间切换?

java - 如何避免 DB4o 数据库中的重复对象

c# - .NET 中的 ElapsedTime 格式

c# - KeyValuePair 与 NameValueCollection

c# - 从 XAML 将枚举值作为命令参数传递

c# - 如何保存而不是另存为

c# - 为什么在 'GET' ing 时会出现此 WCF 错误?

c# - 应用程序错误 System.InvalidOperationException : An unspecified error occurred on the render thread

c# - 使用 Base64 字符串在 MVC Webgrid 中下载问题