加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – 自定义数组排序

发布时间:2020-12-16 01:53:12 所属栏目:百科 来源:网络整理
导读:我的数组中的每个项目/字符串以两个字母开头,后跟两个或三个数字,然后有时后跟另一个字母. 例如,RS01 RS10 RS32A RS102 RS80 RS05A RS105A RS105B 我尝试使用默认的Array.Sort对此进行排序,但它回来了… RS01RS05ARS10RS102RS105ARS105BRS32ARS80 但我需要这
我的数组中的每个项目/字符串以两个字母开头,后跟两个或三个数字,然后有时后跟另一个字母.

例如,RS01 RS10 RS32A RS102 RS80 RS05A RS105A RS105B

我尝试使用默认的Array.Sort对此进行排序,但它回来了…

RS01
RS05A
RS10
RS102
RS105A
RS105B
RS32A
RS80

但我需要这样的..

RS01
RS05A
RS10
RS32A
RS80
RS102
RS105A
RS105B

有任何想法吗?

解决方法

这是使用自定义比较委托和正则表达式进行排序:

string[] array = { "RS01","RS10","RS32A","RS102","RS80","RS05A","RS105A","RS105B" };

Array.Sort(array,(s1,s2) =>
    {
        Regex regex = new Regex(@"([a-zA-Z]+)(d+)([a-zA-Z]*)");
        var match1 = regex.Match(s1);                                        
        var match2 = regex.Match(s2);

        // prefix
        int result = match1.Groups[1].Value.CompareTo(match2.Groups[1].Value);
        if (result != 0)
            return result;

        // number 
        result = Int32.Parse(match1.Groups[2].Value)
                        .CompareTo(Int32.Parse(match2.Groups[2].Value));

        if (result != 0)
            return result;

        // suffix
        return match1.Groups[3].Value.CompareTo(match2.Groups[3].Value);
    });

更新(重构很少,并将所有内容移动到单独的比较器类).用法:

Array.Sort(array,new RSComparer());

比较自己:

public class RSComparer : IComparer<string>
{
    private Dictionary<string,RS> entries = new Dictionary<string,RS>();

    public int Compare(string x,string y)
    {
        if (!entries.ContainsKey(x))
            entries.Add(x,new RS(x));

        if (!entries.ContainsKey(y))
            entries.Add(y,new RS(y));

        return entries[x].CompareTo(entries[y]);
    }

    private class RS : IComparable
    {
        public RS(string value)
        {
            Regex regex = new Regex(@"([A-Z]+)(d+)([A-Z]*)");
            var match = regex.Match(value);
            Prefix = match.Groups[1].Value;
            Number = Int32.Parse(match.Groups[2].Value);
            Suffix = match.Groups[3].Value;
        }

        public string Prefix { get; private set; }
        public int Number { get; private set; }
        public string Suffix { get; private set; }

        public int CompareTo(object obj)
        {
            RS rs = (RS)obj;
            int result = Prefix.CompareTo(rs.Prefix);
            if (result != 0)
                return result;

            result = Number.CompareTo(rs.Number);
            if (result != null)
                return result;

            return Suffix.CompareTo(rs.Suffix);
        }
    }
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读