本文介绍了按日期对字符串列表进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想按日期对字符串列表进行排序.我收到的字符串的格式如下所示:

I'm looking to sort a String List by date. The string I receive is in the form displayed below:

  • 2017年1月1日,苏格兰,五月初的银行假期
  • 2016年1月1日,夏季假日,苏格兰
  • 2014年1月1日至2日,苏格兰圣安德鲁节
  • 2017年4月14日,耶稣受难日,英格兰和威尔士

即使子字符串的长度可变,是否有一种获取日期的方法,如果它是一位数字的话,不将0附加到初始数字上吗?我尝试使用 Regex.Match(),但似乎无法找出处理前几位数字的最佳方法:

Is there a way to get the date, even though the sub-string is variable in length, without appending a 0 to the initial number if it's a single digit? I've tried using Regex.Match() with a but can't seem to work out the best way to handle the first few digits:

Match match = Regex.Match(toBeInsertedList.ToString(), @"\d{1}-\d{2}-\d{4}");
string date = match.Value;
var combineList = DateTime.ParseExact(date, "dd/MM/yyyy", CultureInfo.CurrentCulture);

我还尝试了以下多种形式的代码:

I've also tried the below code in its many forms:

var orderedList = toBeInsertedList.OrderByDescending(x => DateTime.Parse(x)).ToList();

任何指导都是好的,因为我仍在学习.

Any guidance would be good, as I'm still learning.

谢谢!

推荐答案

另一种想法是使用string.Split(',')在逗号字符上分割字符串,并从结果数组中获取第一项作为日期字符串,然后使用DateTime.ParseExact()将字符串解析为有效日期:

A different idea is to use string.Split(',') to split your string on the comma character and grab the first item from the resulting array as the date string, and then use DateTime.ParseExact() to parse the string into a valid date:

static void Main()
{
    var lines = new List<string>
    {
        "1-05-2017,Early May bank holiday, scotland",
        "1-08-2016,Summer bankholiday, scotland",
        "1-12-2014,St Andrew's Day,scotland",
        "14-04-2017,Good Friday, england-and-wales"
    };

    var orderedLines = lines.OrderByDescending(x =>
        DateTime.ParseExact(x.Split(',')[0], "d-MM-yyyy",
            CultureInfo.InvariantCulture)).ToList();

    foreach (var line in orderedLines)
    {
        Console.WriteLine(line);
    }

    Console.CursorVisible = false;
    Console.Write("\nPress any key to exit...");
    Console.ReadKey();
}

请注意,结果是以我的本地文化格式打印出来的:

Note that the result is printing out in my local culture format:

这篇关于按日期对字符串列表进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-21 12:06