【问题标题】:Order string contains number (Linq, C#) [duplicate]订单字符串包含数字(Linq,C#)[重复]
【发布时间】:2019-11-09 04:28:21
【问题描述】:

我有带数字的字符串:

string s1 = "cos555cos";
string s2 = "coscos1";
string s3 = "22coscos";
string s4 = "333coscos";
string s5 = "cosco444s";

我列了一个清单:

IList<string> test = new List<string>();
test.Add(s1);
test.Add(s2);
test.Add(s3);
test.Add(s4);
test.Add(s5);

如何按编号订购。结果应该是这样的:

s2, s3, s4, s5, s1

foreach (var item in test)
{
    Console.WriteLine(item);
}

【问题讨论】:

  • 如何订购BBBB123BBBAAAA123AAA
  • 22BBBBB333

标签: c# regex string linq sorting


【解决方案1】:
    string s1 = "cos555cos";
    string s2 = "coscos1";
    string s3 = "22coscos";
    string s4 = "333coscos";
    string s5 = "cosco444s";


    IList<string> test = new List<string>();
    test.Add(s1);
    test.Add(s2);
    test.Add(s3);
    test.Add(s4);
    test.Add(s5);


    var orderedEnumerable = test.OrderBy(StripNumeric);

    foreach (string s in orderedEnumerable)
    {
        Console.WriteLine(s);
    }


    int StripNumeric(string input)
    {
        Regex digitsOnly = new Regex(@"[^\d]");
        return int.Parse(digitsOnly.Replace(input, ""));
    }

【讨论】:

    【解决方案2】:

    通过将此正则表达式的匹配转换为 int 对其进行排序:

    \d+
    

    类似:

    Regex r = new Regex(@"\d+");
    IList<string> test2 = new List<string>();
    foreach(var item in test)
    {
        Match match = r.match(item);
        test2.Add(match[0]);
    }
    Sort(test2);
    

    【讨论】:

    • 嗨,这有什么问题 match[0]);Sort ?我知道进入 foreach 需要 test2 或 ....
    • 这只是想法。
    猜你喜欢
    • 1970-01-01
    • 2019-08-20
    • 1970-01-01
    • 2019-09-22
    • 2012-11-14
    • 2011-08-31
    • 1970-01-01
    • 2012-04-23
    相关资源
    最近更新 更多