How to Sort this String in Ascending Alphanumeric

可紊 提交于 2020-11-28 03:22:30

问题


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".

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

回答1:


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



回答2:


 var sort = strTest.OrderBy(x => int.Parse(x.Replace("B",string.Empty)));

output: B1,B2,B3,B10




回答3:


Replace B with empty string and convert the remaining string into number.

var sort = strTest.OrderBy(x => Convert.ToInt32(x.Replace("B", "")));



回答4:


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)));


来源:https://stackoverflow.com/questions/17270045/how-to-sort-this-string-in-ascending-alphanumeric

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!