[英]How to Sort this String in Ascending Alphanumeric
I have the following list of string我有以下字符串列表
var strTest = new List<string> { "B2", "B1", "B10", "B3" };
I want to sort them as follows "B1, B2, B3, B10".我想将它们排序如下“B1,B2,B3,B10”。
If I use LINQ OrderBy it sorts this way "B1, B10, B2, B3"如果我使用 LINQ OrderBy 它以这种方式排序“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();
}
try this:尝试这个:
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));
});
var sort = strTest.OrderBy(x => int.Parse(x.Replace("B",string.Empty)));
输出:B1,B2,B3,B10
将B
替换为空字符串并将剩余的字符串转换为数字。
var sort = strTest.OrderBy(x => Convert.ToInt32(x.Replace("B", "")));
you may try this你可以试试这个
var strTest = new List<string> { "B2", "B1", "B10", "B3" };
var res = strTest.OrderBy(x=> int.Parse(x.Split('B')[1]));
or,或者,
var strTest = new List<string> { "B2", "B1", "B10", "B3" };
var res = strTest.OrderBy(x=> int.Parse(x.Remove(0,1)));
something like就像是
public static string PadNumbers(string input)
{
return Regex.Replace(input, "[0-9]+", match => match.Value.PadLeft(10, '0'));
}
then然后
var result = partNumbers.OrderBy(x => PadNumbers(x));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.