Linq按日期排序

时间:2016-12-12 11:33:27

标签: c# linq sorting

我有以下格式的日期字符串列表

Apr-2016
Aug-2015
Nov-2015
Oct-2015
Sep-2015
July 2016

代码:

var sortedMonths = monthList
            .Select(x => new { month = x, Sort = DateTime.ParseExact(x, "MMM-yyyy", CultureInfo.InvariantCulture) })
            .OrderByDescending(x => x.Sort.Month)
            .Select(x => x.month)
            .ToList();

我已经习惯了以上陈述,但列表仍未订购。

2 个答案:

答案 0 :(得分:7)

尝试按整个DateTime对象排序,而不仅仅是月份:

var sortedMonths = monthList
            .Select(x => new { month = x, Sort = DateTime.ParseExact(x, "MMM-yyyy", CultureInfo.InvariantCulture) })
            .OrderByDescending(x => x.Sort)
            .Select(x => x.month)
            .ToList();

答案 1 :(得分:1)

请确保日期字符串格式正确。

July-2016

应该是

Jul-2016

以下是按日期降序排序的工作示例

using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Globalization;

public class TestSortDateStrings
{
    public static void Main()
    {
        var monthList = new List<string> {"Apr-2016", "Aug-2015", "Nov-2015", "Oct-2015", "Sep-2015", "Jul-2016"};
        var sortedMonths = monthList
            .Select(x => new { month = x, Sort = DateTime.ParseExact(x, "MMM-yyyy", CultureInfo.InvariantCulture) })
            .OrderByDescending(x => x.Sort)
            .Select(x => x.month)
            .ToList();

        foreach(var m in sortedMonths)
        {
            Console.WriteLine(m);
        }
    }
}

如果您先按年份按月按月分类

,您将获得相同的结果
.OrderByDescending(x => x.Sort.Year)
.ThenByDescending(x => x.Sort.Month)

输出

Jul-2016
Apr-2016
Nov-2015
Oct-2015
Sep-2015
Aug-2015