按日期对字符串列表进行排序

编程入门 行业动态 更新时间:2024-10-25 22:31:33
本文介绍了按日期对字符串列表进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

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

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:

更多推荐

按日期对字符串列表进行排序

本文发布于:2023-10-18 03:21:30,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1502926.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:字符串   按日   列表

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!