How to organize an Array by Time order?

0

I have two lists with the format of TimeSpan and another with format of String . I need to organize these two lists for ascending and descending.

        List<string> horaString = new List<string>() 
        { 
          "01:04:00",
          "04:04:00",
          "02:02:10",
          "03:05:00",
          "10:07:00",
          "22:20:00"
        };

        List<TimeSpan> horaTimespan = new List<TimeSpan>() 
        { 
          new TimeSpan(5, 30, 1),
          new TimeSpan(2, 15, 5), 
          new TimeSpan(7, 32, 1),
          new TimeSpan(8, 15, 5), 
          new TimeSpan(1, 23, 1),
          new TimeSpan(3, 15, 5) 
        };
    
asked by anonymous 08.03.2018 / 01:28

2 answers

4

You can use the OrderBy and OrderByDescending method.

        List<string> horaString = new List<string>()
        {
          "01:04:00",
          "04:04:00",
          "02:02:10",
          "03:05:00",
          "10:07:00",
          "22:20:00"
        };


        List<TimeSpan> horaTimespan = new List<TimeSpan>()
        {
          new TimeSpan(5, 30, 1),
          new TimeSpan(2, 15, 5),
          new TimeSpan(7, 32, 1),
          new TimeSpan(8, 15, 5),
          new TimeSpan(1, 23, 1),
          new TimeSpan(3, 15, 5)
        };

        horaString = horaString.OrderBy(p => p).ToList();
        horaTimespan = horaTimespan.OrderBy(p => p.Hours).ToList();

        Console.WriteLine("String crescente");
        horaString.ForEach(p => Console.WriteLine(p));

        Console.WriteLine("Time Span crescente");
        horaTimespan.ForEach(p => Console.WriteLine(p));

        horaString = horaString.OrderByDescending(p => p).ToList();
        horaTimespan = horaTimespan.OrderByDescending(p => p.Hours).ToList();

        Console.WriteLine("String decrescente");
        horaString.ForEach(p => Console.WriteLine(p));

        Console.WriteLine("Time Span decrescente");
        horaTimespan.ForEach(p => Console.WriteLine(p));

See working at .Net Fiddle

    
08.03.2018 / 02:35
1

Look for Split String in C # (to split the string into string array, separating by ":" (colon)), then transform the 3 string into a single integer value (creating a list of integers) p>

hora = array[0];
minuto = array[1];
segundos = array[2];
valor = hora*3600 + minuto*60 + segundos

, and sort by using the example

link .

Then return the integer to the original value

hora = valor/3600;
valor -= hora*3600;
minuto = valor/60;
valor -= minuto*60;
segundos = valor;
    
08.03.2018 / 01:43