如何将 C# 中的列表按月排序?

How can I sort my List in C# to the Month?

所以我在 C# 中得到了一个包含许多不同日期的字符串列表。现在我想要做的是将所有这些日期排序为月份。这意味着,我希望代表的每个月都以此日期格式创建一个字符串:YYYY0MM。

所以当我得到这些日期时:

01.02.2003

05.02.2003

15.02.2004

24.03.2003

这个字符串转换中的这些日期:

字符串 1 值:2003002

字符串 2 值:2004002

字符串 3 值:2003003

我认为这对你有帮助:

            var dates = new List<string>() { "01.02.2003", "05.02.2003", "15.02.2004", "24.03.2003"};
            var result = new List<string>();
            dates.ForEach(dateItem =>
            {
            DateTime dateValue;
            if (DateTime.TryParse(dateItem, out dateValue))
            {
                result.Add($"{ dateValue.Year}0{dateValue.Month.ToString().PadLeft(2,'0')}");
                }
            });

在 运行 之后,此代码段的“结果”变量值将为:{"2003002","2003002","2004002","2003003"}

我认为诀窍是将日期转换为每个月的第一天,然后执行不同操作以删除重复项并按月排序:

string[] input = { "01.02.2003", "05.02.2003", "15.02.2004", "24.03.2003" };

string[] output = input
.Select(x => DateTime.ParseExact(x, "dd.MM.yyyy", CultureInfo.InvariantCulture)) //parse the strings to dates
.Select(x => x.AddDays(1 - x.Day)) //get first day of each month
.Distinct() //remove the duplicates
.OrderBy(x => x.Month) //order by month
.Select(x => x.ToString("yyyy0MM")).ToArray();