Advertisement
kyrathasoft

Demo sorting List<DateTime> ascending and descending

Jun 14th, 2019
361
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.53 KB | None | 0 0
  1. using System;
  2. using System.Collections.Generic;
  3.  
  4. namespace ExampleOfOrderingByDate {
  5.  
  6.     class OrderingByDate{
  7.        
  8.         public static List<DateTime> myList;
  9.    
  10.         public static void Main(string[] args){
  11.        
  12.             /* Important: before invoking Reverse() on a list of dates, you must first invoke .Sort();
  13.                .Sort sorts dates in ascending order, and then Reverse() reverses THAT ordering */
  14.                
  15.             PopulateTheList();
  16.            
  17.             Console.WriteLine(" The populated list 'myList' contains {0} DateTime item(s):", myList.Count);
  18.             Console.Write(" Unsorted order: ");
  19.             EnumerateTheList();
  20.            
  21.             Console.Write(" Sort ascending: ");
  22.             myList.Sort();
  23.             EnumerateTheList();
  24.            
  25.             Console.Write(" Sort descending: ");
  26.             myList.Reverse();
  27.             EnumerateTheList();
  28.         }
  29.        
  30.         public static void EnumerateTheList(){
  31.             foreach(DateTime dt in myList){
  32.                 Console.Write(dt.ToShortDateString() + " ");
  33.             }
  34.             Console.WriteLine();            
  35.         }
  36.        
  37.         public static void PopulateTheList(){
  38.             myList = new List<DateTime>();
  39.             myList.Add(DateTime.Parse("8/6/1937"));
  40.             myList.Add(DateTime.Parse("6/15/1977"));
  41.             myList.Add(DateTime.Parse("2/15/1947"));
  42.             myList.Add(DateTime.Parse("3/15/1973"));
  43.             myList.Add(DateTime.Parse("7/26/1971"));
  44.         }
  45.    
  46.     }
  47.  
  48. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement