简体   繁体   English

C#中的字符串排序错误

[英]Wrong string ordering in C#

I ran this: 我跑了这个:

void Main()
{
    List<string> strings = new List<string>{"aaa", "z", "a"};
    Console.WriteLine(string.Join("\n", strings.OrderBy(k => k)));
}

And the output is: 输出为:

a
z
aaa

This can't be right! 这是不对的! I was expecting 我期待

a
aaa
z

What could be the problem? 可能是什么问题呢?

I've realized that OrderBy uses the current locale to sort strings. 我已经意识到OrderBy使用当前语言环境对字符串进行排序。 In my case the locale is Danish, in which "aa" comes after "z", as it represents the letter "å", which is appended at the end of the alphabet. 在我的情况下,语言环境是丹麦语,其中“ aa”在“ z”之后,因为它代表字母“å”,该字母附加在字​​母的末尾。

This came as a surprise to me because I was expecting English sorting and I hadn't realized that the locale had been Danish all along; 这让我感到惊讶,因为我期待英语排序,而且我还没有意识到语言环境一直都是丹麦语。 many other settings on my system are set to English, including the language. 我系统上的许多其他设置都设置为英语,包括语言。 This tricked my expectation into being wrong. 这欺骗了我的期望是错误的。

To get the ordering I expect, it was sufficient to pass StringComparer.InvariantCulture to OrderBy : 为了获得我期望的排序,将StringComparer.InvariantCulture传递给OrderBy就足够了:

void Main()
{
    List<string> strings = new List<string>{"aaa", "z", "a"};
    Console.WriteLine(string.Join("\n", strings.OrderBy(k => k, StringComparer.InvariantCulture)));
}

Output: 输出:

a
aaa
z

That's happen because your default comparer sorts by length first. 发生这种情况是因为您的默认比较器首先按长度排序。 You didn't try to sort a collection with mixed cases, like: 您没有尝试对混合大小写的集合进行排序,例如:

List<string> strings = new List<string>{"aaa", "D", "z", "a"};

In the answer posted by elnigno it will produce an output like: 在elnigno发布的答案中,它将产生如下输出:

a
aaa
D
z

If you need to have them ordered by their codes in coding table, then most likely you'll prefer this way: 如果您需要按照编码表中的代码对它们进行排序,那么很可能您会喜欢这种方式:

var keywords = new List<string> { "aaa", "D", "z", "a" };
Console.WriteLine(string.Join("\n", keywords.OrderBy(k => k, StringComparer.Ordinal)));

And output will be like: 输出将是这样的:

D
a
aaa
z

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM