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

查看:144
本文介绍了在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

在那里,因为我期待的结果。

where as I am expecting the results as

-
.
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天全站免登陆