Sort string list with dates in C#

前端 未结 6 1591
不知归路
不知归路 2020-12-31 07:00

I have a List with dates.
My list is:

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

I want to sort the list

6条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-31 07:49

    You shouldn't use string representations of data - we're all living in object-oriented world :)

    Best way would be to convert these strings into actual DateTime objects and sort them in reverse order via linq:

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

    Another way would be to implement custom sorting function, see this link. Then you'd just use it in a sort function:

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

提交回复
热议问题