How to sort a List of Strings?

2

I have List<List<string>> and need to sort the main list according to some elements of the secondary see the illustration below.

Ineedthefirstleveltobeinalphabeticalorder,andthesecondlevelisinascendingorderbutaccordingtothenumbers.Forexamplethenumber26hastocomebefore1000.

Thecodebelowdoessomethingsimilarbutatthesecondlevelitsortsaccordingtostring,sothe1000comesbeforethe26th.

varMySortedList=MyUnsortedList.OrderBy(x=>x[1]).ThenBy(x=>x[2]);

IwouldhavetoconvertittointanddothesortinghoweverinsomestringsIhave/and-.InthiscaseitwouldhaveaException.Ihavenoideahowtoimplementit.

    
asked by anonymous 30.01.2017 / 23:57

1 answer

3

This will probably work:

using System;
using System.Collections.Generic;
using System.Linq;

public class Program {
    public static void Main() {
        var lista = new List<string> { "12/10", "01/02", "123/12", "A/1", "4/5" };
        var listaClassificada = lista.OrderBy(x => ConversaoParcial(x));
        listaClassificada.ToList().ForEach(Console.WriteLine);
    }
    public static string ConversaoParcial(string texto) {
        int valor;
        string textoParcial = texto.Split('/', '-')[0];
        return int.TryParse(textoParcial, out valor) ? textoParcial.PadLeft(4, '0') : textoParcial.PadLeft(4, 'A');
    }
}

See working on .NET Fiddle . And No Coding Ground . Also put it on GitHub for future reference .

31.01.2017 / 01:11