Dictionary sort by datetime
C# Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 | class Program { static void Main(string[] args) { //initialize a dictionary with date time values. Dictionary<int, DateTime> dc = new Dictionary<int, DateTime>() { {1,DateTime.Today}, {2,DateTime.Today.AddDays(3)}, {3,DateTime.Today.AddDays(1)}, {4,DateTime.Today.AddDays(10)}, {5,DateTime.Today.AddDays(5)}, }; Console.WriteLine("dictionary keys and values.........."); foreach (KeyValuePair<int, DateTime> pair in dc) { Console.WriteLine(pair.Key + " ........ " + pair.Value.ToShortDateString()); } //ascending sorted dictionary by date time value. dc = dc.OrderBy(x => x.Value).ToDictionary(x => x.Key, x => x.Value); Console.WriteLine("ascending sorted dictionary by date time value.........."); foreach (KeyValuePair<int, DateTime> pair in dc) { Console.WriteLine(pair.Key + " ........ " + pair.Value.ToShortDateString()); } //descending sorted dictionary by date time values. dc = dc.OrderByDescending(x => x.Value).ToDictionary(x => x.Key, x => x.Value); Console.WriteLine("descending sorted dictionary by date time values.........."); foreach (KeyValuePair<int, DateTime> pair in dc) { Console.WriteLine(pair.Key + " ........ " + pair.Value.ToShortDateString()); } Console.ReadLine(); } } |
Output: