Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Split String to array and Sort Array

I am trying to sort a string split by comma. But it is not behaving as expected

var classes = "10,7,8,9";
Console.Write(string.Join(",", classes.Split(',').OrderBy(x => x)));
Console.ReadKey();

and output is

10,7,8,9

But I want the expected output to be like:

7,8,9,10

Classes can have a section along with them. like 7a,7b

and I want to achieve it on one line of code.

like image 760
Imran Ahmad Shahid Avatar asked Aug 08 '17 06:08

Imran Ahmad Shahid


Video Answer


2 Answers

You can use Regex like this

var classes = "10,7,8,9";
Regex number = new Regex(@"^\d+");
Console.Write(string.Join(",", classes.Split(',').OrderBy(x => Convert.ToInt32(number.Match(x).Value)).ThenBy(x => number.Replace(x, ""))));
Console.ReadKey();
like image 156
Kahbazi Avatar answered Oct 06 '22 00:10

Kahbazi


CODE:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
using System.Collections;
namespace Rextester
{
    public class Program
    {
        public static void Main(string[] args)
        {
            var l = new List<string> { "1D", "25B", "30A", "9C" };
    l.Sort((b, a) =>
    {
        var x = int.Parse(Regex.Replace(a, "[^0-9]", ""));
        var y = int.Parse(Regex.Replace(b, "[^0-9]", ""));
        if (x != y) return y - x;
        return -1 * string.Compare(a, b);
    });

    foreach (var item in l) Console.WriteLine(item);

        }
    }
}

OUTPUT: 1D 9C 25B 30A

ONLINE COMPILE: http://rextester.com/CKKQK66159

like image 40
huse.ckr Avatar answered Oct 06 '22 00:10

huse.ckr