Saturday, 2 February 2013

C# Sort DateTime Array

C# Sort DateTime Array


Suppose String array  as Dates in this format. DD-MMM-YYYY format.

String[] dtArra = new String[] {"12-jan-2001","12-feb-1973","7-Mar-1876","6-Dec-1967"};


If u want to sort using LINQ.
 This is ascending order of dates.

            var query = from d in dtArra
                        orderby
                        DateTime.ParseExact(d,
                        "%d-MMM-yyyy",
                        new System.Globalization.CultureInfo(1033))
                        select d;

            foreach (String str in query)
            {
                Console.WriteLine(str);
            }
 

Dates Ascending Order

7-Mar-1876
6-Dec-1967
12-feb-1973
12-jan-2001
 
 This is descending order of dates.


            var query = from d in dtArra
                        orderby
                        DateTime.ParseExact(d,
                        "%d-MMM-yyyy",
                        new System.Globalization.CultureInfo(1033)) descending
                        select d;

            foreach (String str in query)
            {
                Console.WriteLine(str);
            }

Dates descending Order

12-jan-2001
12-feb-1973
6-Dec-1967
7-Mar-1876

Tags:C# Sort DateTime Array,dates Ascending order using LINQ,dates descending order using LINQ, Sorting DateTime Array Strings.LINQ Order by DateTime.ParaseExact