如何按升序字母数字对该字符串排序 [英] How to Sort this String in Ascending Alphanumeric
本文介绍了如何按升序字母数字对该字符串排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有以下字符串列表
var strTest = new List<string> { "B2", "B1", "B10", "B3" };
我想按"B1,B2,B3,B10"对它们进行排序.
I want to sort them as follows "B1, B2, B3, B10".
如果我使用LINQ OrderBy,它的排序方式为"B1,B10,B2,B3"
If I use LINQ OrderBy it sorts this way "B1, B10, B2, B3"
请帮助.这是我的代码.
Please help. Here's my code.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace SortingDemo
{
class Program
{
static void Main(string[] args)
{
var strTest = new List<string> { "B2", "B1", "B10", "B3" };
var sort = strTest.OrderBy(x => x);
var sortedStr = string.Join(",", sort);
Console.WriteLine(sortedStr);
Console.ReadLine();
}
推荐答案
尝试一下:
var strTest = new List<string> { "B1", "B2", "B3", "B10" };
strTest.Sort((s1, s2) =>
{
string pattern = "([A-Za-z])([0-9]+)";
string h1 = Regex.Match(s1, pattern).Groups[1].Value;
string h2 = Regex.Match(s2, pattern).Groups[1].Value;
if (h1 != h2)
return h1.CompareTo(h2);
string t1 = Regex.Match(s1, pattern).Groups[2].Value;
string t2 = Regex.Match(s2, pattern).Groups[2].Value;
return int.Parse(t1).CompareTo(int.Parse(t2));
});
这篇关于如何按升序字母数字对该字符串排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文