1

我有以下字符串列表

var strTest = new List<string> { "B2", "B1", "B10", "B3" };

我想将它们排序如下“B1,B2,B3,B10”。

如果我使用 LINQ OrderBy 它以这种方式排序“B1,B10,B2,B3”

请帮忙。这是我的代码。

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();
        }
4

4 回答 4

4

试试这个:

    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));
    });
于 2013-06-24T07:29:15.347 回答
3
 var sort = strTest.OrderBy(x => int.Parse(x.Replace("B",string.Empty)));

输出:B1,B2,B3,B10

于 2013-06-24T07:28:51.443 回答
1

替换B为空字符串并将剩余的字符串转换为数字。

var sort = strTest.OrderBy(x => Convert.ToInt32(x.Replace("B", "")));
于 2013-06-24T07:25:45.363 回答
1

你可以试试这个

   var strTest = new List<string> { "B2", "B1", "B10", "B3" };

   var res = strTest.OrderBy(x=> int.Parse(x.Split('B')[1]));

或者,

  var strTest = new List<string> { "B2", "B1", "B10", "B3" };
  var res = strTest.OrderBy(x=> int.Parse(x.Remove(0,1)));
于 2013-06-24T07:43:56.260 回答