且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

排序字符串数字

更新时间:2023-02-23 09:52:02

根据之前的评论,我还将实现一个自定义的 IComparer 类.据我所知,项目的结构要么是一个数字,要么是一个数字后跟一个字母的组合.如果是这种情况,以下 IComparer 实现应该可以工作.

Going by the previous comments, I would also implement a custom IComparer<T> class. From what I can gather, the structure of the items is either a number, of a combination of a number followed by a letter(s). If this is the case, the following IComparer<T> implementation should work.

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,你就可以对你的string列表进行排序

With this IComparer<T>, you'll be able to sort your list of string by doing

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

已使用以下项目进行测试:

This has been tested with the following items:

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