How to organize an Array by Date order?

1

I'm trying to organize an array by ascending date order. I was thinking of cutting the parts using the (/) bar and compare it with the other parts, but I do not know if that's the best way to do it.

I need to organize the array below:

List<string> datas = new List<string>();
  

0 [02/05/2018]

     

1 [01/04/2018]

     

2 [07/03/2018]

     

3 [06/02/2018]

     

4 [09/01/2018]

    
asked by anonymous 28.02.2018 / 22:55

2 answers

5

You can use Linq to convert the list of strings to a list of dates and sort them.

Example

var orderedDates = datas.OrderBy(x => DateTime.ParseExact(x,"dd/MM/yyyy", CultureInfo.InvariantCulture));

See working at dot.net Fiddle

    
28.02.2018 / 23:32
1

Follow the code below, I hope I have helped

static void Main(string[] args)
    {
        //Populando sua lista
        var datas = new List<string>() {
            "02/05/2018",
            "01/04/2018",
            "07/03/2018",
            "06/02/2018",
            "09/01/2018",
        };

        //Ordenando datas com OrderBy e atribuindo o resultado em "datasOrdemCrescente"
        var datasOrdemCrescente = datas.OrderBy(c => Convert.ToDateTime(c));

        //Imprimir resultado datasOrdemCrescente
        foreach (var item in datasOrdemCrescente)
        {
            Console.WriteLine(item);
        }

        Console.WriteLine("---------------");

        //Ordenando datas com OrderByDescending e atribuindo o resultado em "datasOrdemDecrescente"
        var datasOrdemDecrescente = datas.OrderByDescending(c => Convert.ToDateTime(c));

        //Imprimir resultado datasOrdemDecrescente
        foreach (var item in datasOrdemDecrescente)
        {
            Console.WriteLine(item);
        }

        Console.ReadKey();
    }
    
01.03.2018 / 13:25