Home > database >  C# Sorting a list of strings that contains numbers 2
C# Sorting a list of strings that contains numbers 2

Time:12-06

I need to sort the List by the numbers in the string while keeping the name with the string. Here is an example of what I have in mind:

An unordered List:

BA05
R01
BA03
MTA008
MTA002
R07

Ordered List:

R01
MTA002
BA03
BA05
R07
MTA008

CodePudding user response:

var unorderedList = new List<string>(){"BA05", "R01", "BA03", "MTA008", "MTA002", "R07"};

var orderedList = unorderedList
    .Select(input => new
    {
        text = input,
        number = int.Parse(Regex.Match(input, @"\d ").Value)
    })
    .OrderBy(x => x.number)
    .Select(x => x.text).ToList();

CodePudding user response:

Here is the solution

 var data = new List<string>() { "BA05", "R01", "BA03", "MTA008", "MTA002", "R07" };
            var sortedList = data.Select(value => new
            {
                Key = Convert.ToInt64(string.Join("", value.Where(x => x >= '0' && x <= '9'))) ,
                Value = value
            })
            .OrderBy(x => x.Key)
            .Select(x => x.Value)
            .ToList();
  • Related