c# - 排序字符串数字

标签 c# string list sorting

<分区>

Possible Duplicate:
Natural Sort Order in C#

我有一个列表,里面有很多数字。 但由于一些额外的字母,它们被保存为字符串。

我的列表看起来像这样:

1
10
11
11a
11b
12
2
20
21a
21c
A1
A2
...

但它应该是这样的

1
2
10
11a
11b
...
A1
A2
...

如何对列表进行排序以获得此结果?

最佳答案

根据之前的评论,我还将实现自定义 IComparer<T>类(class)。据我所知,项目的结构要么是数字,要么是数字后跟字母的组合。如果是这种情况,以下IComparer<T>实现应该有效。

public class CustomComparer : IComparer<string>
{
    public int Compare(string x, string y)
    {
        var regex = new Regex("^(d+)");

        // run the regex on both strings
        var xRegexResult = regex.Match(x);
        var yRegexResult = regex.Match(y);

        // check if they are both numbers
        if (xRegexResult.Success && yRegexResult.Success)
        {
            return int.Parse(xRegexResult.Groups[1].Value).CompareTo(int.Parse(yRegexResult.Groups[1].Value));
        }

        // otherwise return as string comparison
        return x.CompareTo(y);
    }
}

有了这个IComparer<T> ,您将能够对 string 的列表进行排序通过做

var myComparer = new CustomComparer();
myListOfStrings.Sort(myComparer);

这已经通过以下项目进行了测试:

2, 1, 4d, 4e, 4c, 4a, 4b, A1, 20, B2, A2, a3, 5, 6, 4f, 1a

并给出结果:

1, 1a, 2, 20, 4a, 4b, 4c, 4d, 4e, 4f, 5, 6, A1, A2, a3, B2

关于c# - 排序字符串数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9988937/

相关文章:

c# - 将样式中的 Setter 值绑定(bind)到主模型

c# - 使用 C# 连接到本地 SQL Server 数据库

java - 只有带控件的数字

.net - 在 F# 中从字符串中去除字符

python - 根据阈值减少列表中元组的数量

c# - 方法和约束的唯一性

iOS (Swift) 应用程序在 JSON 解析时崩溃

python - 将列表附加到字典以获取嵌套列表

Python 循环缺少结果

c# - WPF:ViewModel 类型不包含任何可访问的构造函数