Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sorting array of formatted time strings

Tags:

arrays

c#

sorting

I am trying to sort my arraylist.

The array list consists of data in time format.

Array:

9:15 AM, 10:20 AM

How should I sort it?

The result i get from below code is :

10:20 AM
9:15 AM

Below is my code:

String timeText = readFileTime.ReadLine();
    timeSplit = timeText.Split(new char[] { '^' });
    Array.Sort(timeSplit);

foreach (var sortedArray in timeSplit)
    {
        sortedTimeListBox.Items.Add(sortedArray);
    }
like image 627
beny lim Avatar asked Mar 15 '26 23:03

beny lim


1 Answers

Yes, since you simply split a string, you're merely sorting an array of strings (meaning 1 comes before 9 and it doesn't care about the decimal point). To get the sorting you desire, you need to first convert it into a DateTime like this:

timeSplit = timeText
    .Split(new char[] { '^' });
    .Select(x => new { Time = DateTime.Parse(x), String = x })
    .OrderBy(x => x.Time)
    .Select(x => x.String)
    .ToArray();

Here, what we've done is:

  1. Split the string as you had done before
  2. Create a new anonymous type that contains the original string and also that string converted into a DateTime.
  3. Ordered it by the DateTime property
  4. Select'ed back to the original string
  5. Converted it into an array

timeSplit now contains the strings sorted as you wanted.

like image 199
Kirk Woll Avatar answered Mar 17 '26 12:03

Kirk Woll



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!