How to organize an Array in order of Time?

Asked

Viewed 124 times

0

I have two lists with format TimeSpan and another with a format of String. I need to organize these two lists for increasing and decreasing.

        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) 
        };
  • Search for Split String in Google (to split the string into string array, separating by ":"(colon)), then transform the 3 string and a single integer value (value = time3600 + minute60 + seconds), and sort it (look for the Quicksort algorithm)

2 answers

4


You can use the method OrderBy and OrderByDescending.

        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 on .Net Fiddle

  • just don’t need the Timespan conversion, if it was date yes,

  • 1

    All right, I’ll adjust

1

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

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

, and order by him using the example

https://stackoverflow.com/questions/3738639/sorting-a-listint.

Then return the integer to the original value

hora = valor/3600;
valor -= hora*3600;
minuto = valor/60;
valor -= minuto*60;
segundos = valor;

Browser other questions tagged

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