开发者

Sorting array of formatted time strings

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 = ti开发者_运维百科meText.Split(new char[] { '^' });
    Array.Sort(timeSplit);

foreach (var sortedArray in timeSplit)
    {
        sortedTimeListBox.Items.Add(sortedArray);
    }


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.


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜