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:
- Split the string as you had done before
- Create a new anonymous type that contains the original string and also that string converted into a
DateTime
. - Ordered it by the
DateTime
property Select
'ed back to the original string- 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));
});
精彩评论