簡體   English   中英

包含數字和字母的排序列表

[英]Sort list that contains numbers and letters

我有字母數字列表,我希望這個順序是第一個數字,然后是降序的字符。

EH40, DH40, DH36,AH40, AH36,EH27S,  DH32,EH32, AH32,  DH27S, EH36

預期結果:

EH40, DH40, AH40, EH36, DH36, AH36 ,EH32, DH32 and so on

嘗試以下操作:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;


namespace ConsoleApplication11
{
    class Program
    {
        const string FILENAME = @"c:\temp\test.xml";
        static void Main(string[] args)
        {
            string[] input = {"EH40", "DH40", "DH36","AH40", "AH36","EH27S", "DH32","EH32", "AH32", "DH27S", "EH36"};

            string[] results = input.Select(x => new AlphaNumeric(x)).OrderBy(x => x).Select(x => x.input).ToArray();

          
        }
  
    }
    public class AlphaNumeric : IComparable<AlphaNumeric>
    {
        string prefix { get; set; }
        int number { get; set; }
        public string input { get; set; }
        static string pattern = @"(?'prefix'.*)(?'number'\d+)[^\d]*$";
        public AlphaNumeric(string input)
        {
            this.input = input;
            Match match = Regex.Match(input, pattern, RegexOptions.RightToLeft);
            string numberStr = match.Groups["number"].Value;
            number = int.Parse(numberStr);
            prefix = match.Groups["prefix"].Value;

        }
        public int CompareTo(AlphaNumeric other)
        {
            int results = 0;

            if (this.number != other.number)
            {
                results = this.number.CompareTo(other.number);
            }
            else
            {
                if (this.prefix == other.prefix)
                {
                    results = this.input.CompareTo(other.input);
                }
                else
                {
                    results = this.prefix.CompareTo(other.prefix);
                }
            }

            return results;
        }
    }

 
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM