用C#中的日期对字符串列表进行排序

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14667754/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 12:38:30  来源:igfitidea点击:

Sort string list with dates in C#

c#listsortingdate

提问by

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

我有一个List<string>日期。
我的清单是:

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

I want to sort the list to look like this:

我想对列表进行排序,使其看起来像这样:

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

How can I make this?

我怎样才能做到这一点?

采纳答案by mipe34

With linq:

使用 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 questions in comments):

更新(根据评论中的问题):

You can treat invalid dates like this (invalid date is there treated as default(DateTime)):

您可以像这样处理无效日期(无效日期被视为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 invalid datetime as 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 the invalid dates out:

您还可以过滤掉无效日期:

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

Or even better:

或者甚至更好:

var filteredList = list.Select(x =>
        {
            DateTime dt;
            return new {valid = DateTime.TryParse(x, out dt), date = dt};
        }).Where(x => x.valid).Select(x => x.date).OrderByDescending(x => x);

回答by Dmitry Reznik

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:

最好的方法是将这些字符串转换为实际的 DateTime 对象,并通过 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);

回答by Simon Whitehead

Because they are the UK/AUS format (Day/Month/Year), you can sort them using OrderByDescending:

因为它们是 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);

Personally I would convert them to DateTimeobjects first..

我个人会DateTime先将它们转换为对象..

回答by spajce

Why do you want to use List<string>instead of List<DateTime>?

为什么要使用List<string>而不是List<DateTime>

List<DateTime> dates = ...

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

回答by Alex Filipovici

Try this:

尝试这个:

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));

回答by Bravo Yeung

To convert DateTime string of custom format to stringof unified format, you can adopt following simple and safesnippet.

要将自定义格式的 DateTime 字符串转换string为统一格式,您可以采用以下简单和safe代码段。

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

Inside the code, formatStrcan be any possible forms the DateTimeclass can accept, you can set it as the format you need, here you can just use dd/MM/yyyywhich is matched with your target format string such as "20/01/2013".

在代码里面,formatStr可以是DateTime类可以接受的任何可能的形式,您可以将其设置为您需要的格式,在这里您可以使用dd/MM/yyyy与您的目标格式字符串匹配的格式,例如“20/01/2013”​​。

So for your case, the code can be simple as below:

因此,对于您的情况,代码可以很简单,如下所示:

    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());

While in some cases, using ParseExactto parse a data time string, it will throws error/exception String was not recognized as a valid DateTime, in that case if you turn to use TryParseExact, the result is probably default(DateTime)= 1/1/0001 12:00:00 AMbecause of parsing failed. Therefore, I do not recommend ParseExactor TryParseExact.

而在某些情况下,ParseExact用于解析数据时间字符串,它会抛出 error/exception String was not recognized as a valid DateTime,在这种情况下,如果您转向 use TryParseExact,结果可能是default(DateTime)=1/1/0001 12:00:00 AM因为解析失败。因此,我不推荐ParseExactTryParseExact