Jobert Enamno Jobert Enamno - 1 month ago 9
C# Question

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

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

Answer

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