3

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);
    }
1
  • You might want to consider converting the values into a proper DateTime structure and utilizing the DateTime.Compare. See dotnetperls.com/sort-datetime for an example. Commented Aug 2, 2011 at 1:38

2 Answers 2

7

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.

Sign up to request clarification or add additional context in comments.

Comments

4
Array.Sort(timeSplit, delegate(string first, string second)
{
    return DateTime.Compare(Convert.ToDateTime(first), Convert.ToDateTime(second));
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.