Sorting a list of rows with dates in C #

I have List<string>with dates.
My list:

{"01/01/2013","10/01/2013","20/01/2013"}

I want to sort the list so that it looks like this:

{"20/01/2013","10/01/2013","01/01/2013"}

How can i do this?

+6
source share
6 answers

With linq:

var list = new List<string> {"01/01/2013", "10/01/2013", "20/01/2013"};
var orderedList = list.OrderByDescending(x => DateTime.Parse(x)).ToList();

UPDATE (according to questions in the comments):

You can consider invalid dates as follows (an invalid date is considered as there default(DateTime)):

var list = new List<string> { "01/01/2013", "10/01/2013", "N/A" , "20/01/2013"  };
var orderedList2 = list.OrderByDescending(x =>
            {
                DateTime dt;
                DateTime.TryParse(x, out dt);
                return dt;
            });

Or, if you want to have an invalid date and time as the first item in the list:

var orderedList3 = list.OrderByDescending(x =>
            {
                DateTime dt;
                if (!DateTime.TryParse(x, out dt)) return DateTime.MaxValue;
                return dt;
            }); 

You can also filter out invalid dates:

var filteredList = list.Where(x =>
            {
                DateTime dt;
                return DateTime.TryParse(x, out dt);
            }).Select(DateTime.Parse).OrderByDescending(x => x);
+21
source

You should not use string representations of data - we all live in an object-oriented world :)

DateTime linq:

var dates = Array.ConvertAll(dateStrings, x => DateTime.Parse(x));
return dates.OrderByDesc(x => x);

, . . :

DateAsStringComparer myComparer = new DateAsStringComparer();
dateStrings.Sort(myComparer);
+4

:

List<string> s = new List<string>() { "01/01/2013", "10/01/2013", "20/01/2013" };
var d = s.OrderByDescending(i => DateTime.ParseExact(i, "dd/MM/yyyy", null));
+3

UK/AUS (//), OrderByDescending:

List<string> dates = new List<string>() { "01/01/2013", "10/01/2013", "20/10/2013" };

foreach (var date in dates.OrderByDescending(x => x))
    Console.WriteLine(date);

DateTime.

0

List<string> List<DateTime>?

List<DateTime> dates = ...

dates.OrderByDescending(c => c).ToList();
0

DateTime string , safe .

    string formatStr = "yyyyMMddHHmmss";
    string result = Convert.ToDateTime(inputStr).ToString(formatStr);

formatStr , DateTime, , dd/MM/yyyy , "20/01/2013".

, :

    List<string> list = new List<string> { "01/01/2013", "10/01/2013", "20/01/2013" };
    var listAfterSorting = list.OrderByDescending(t => 
        Convert.ToDateTime(t).ToString("dd/MM/yyyy")
            .ToList());

ParseExact ParseExact /, String was not recognized as a valid DateTime, , TryParseExact, , , default(DateTime)= 1/1/0001 12:00:00 AM - 1/1/0001 12:00:00 AM . ParseExact TryParseExact.

0

All Articles