C#中的字符串排序问题 [英] String sorting issue in C#

查看:20
本文介绍了C#中的字符串排序问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这样的列表

    List<string> items = new List<string>();
    items.Add("-");
    items.Add(".");
    items.Add("a-");
    items.Add("a.");
    items.Add("a-a");
    items.Add("a.a");

    items.Sort();

    string output = string.Empty;
    foreach (string s in items)
    {
        output += s + Environment.NewLine;
    }

MessageBox.Show(output);

输出返回为

-
.
a-
a.
a.a
a-a

我期待的结果

-
.
a-
a.
a-a
a.a

知道为什么a-a"不在a.a"之前,而a-"在a"之前.

Any idea why "a-a" is not coming before "a.a" where as "a-" comes before "a."

推荐答案

如果您希望字符串排序基于实际字节值而不是当前区域性定义的规则,您可以按序数排序:

If you want your string sort to be based on the actual byte value as opposed to the rules defined by the current culture you can sort by Ordinal:

items.Sort(StringComparer.Ordinal);

这将使结果在所有文化中保持一致(但它会产生14"排在9"之前的不直观的排序,这可能是也可能不是您正在寻找的).

This will make the results consistent across all cultures (but it will produce unintuitive sortings of "14" coming before "9" which may or may not be what you're looking for).

这篇关于C#中的字符串排序问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆