C# Sort DateTime in List<>
Posted: 20/02/2012 Filed under: Programming | Tags: C#, Collections 2 Comments »Do you need to sort your list of objects/types by DateTime? The snippet sample below shows you how.
UPDATED 21/02/2012
1: using System;
2: using System.Collections.Generic;
3: using System.Linq;
4:
5: static void Main(string[] args)
6: {
7: var times = new List<string>
8: {
9: "18 APR 6:30 AM",
10: "14 MAR 4:50 PM",
11: "17 APR 3:15 PM",
12: "14 MAR 11:25 AM",
13: "22 OCT 11:25 PM"
14: };
15:
16: #region Appended
17:
18: var temp = new List<string>();
19:
20: // Split the string then add in year value into new string.
21: // The new string format can be converted to a DateTime type.
22: // Add new string into a new collection.
23: for (var i = 0; i < times.Count; i++)
24: {
25: var splitTime = times[i].Split(' ');
26: var newTimeFormat = splitTime[0] + " " + splitTime[1] + " 2012 " + splitTime[2] + " " + splitTime[3];
27:
28: temp.Add(newTimeFormat);
29: }
30:
31: #endregion
32:
33: #region Updated
34:
35: var list = temp.Select(Convert.ToDateTime).ToList();
36: // The above line is equilevant to the line below.
37: // var list = times.Select(t => Convert.ToDateTime(t)).ToList();
38:
39: #endregion
40:
41: list.Sort(DateTime.Compare);
42: // The above line is equilevant to the line below.
43: // list.Sort((d1, d2) => DateTime.Compare(d1, d2));
44:
45: foreach (var date in list)
46: {
47: Console.WriteLine(date);
48: }
49: }
Hope this helps.
var list = times.Select(Convert.ToDateTime).ToList();
String was not recognized as a valid DateTime.
Hi Khnum,
Thanks for spotting this, obviously my string within the collection is in the wrong format for a DateTime conversion. Please see updated snippet for a working sample, note the Appended and Updated region.
Regards,
Harish