How to organize an Array in Date order?

Asked

Viewed 675 times

1

I am wanting to organize an array by Crescent date order. I was thinking of cutting the parts using the bar (/) and compare with the other parts, but I don’t know if it’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]

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

Watch it work on the Fiddle dot.net

  • Your answer is right, but it is a tip to convert the string to date only in OrderBy. That’s because AP probably wants to simulate that the structure stays the same.

  • Well noted @LINQ, I will add to the reply.

1

Follow the code below, I hope I’ve 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();
    }

Browser other questions tagged

You are not signed in. Login or sign up in order to post.