C#按两个日期排序列表

时间:2017-03-09 16:09:53

标签: c# linq

我有一个包含以下日期的列表

03/05/2017
03/03/2017
03/04/2017
12/15/2016
12/20/2016
12/30/2016

我想在过去7天内将列表从最旧到最新排序,最新到最近过去90天

最终结果应如下所示

03/03/2017
03/04/2017
03/05/2017
12/30/2016
12/20/2016
12/15/2016

FilteredList.OrderBy(x => ReportDate < DateTime.Today.AddDays(-7))
    .ThenBy(x => ReportDate < DateTime.Today.AddDays(-90))

可以这样做吗?

2 个答案:

答案 0 :(得分:4)

可能有效的一种方法是使用查找:

var lastWeekOrBefore = FilteredList.ToLookup(x => x.ReportDate >= DateTime.Today.AddDays(-7));

现在你有一个像Dictionary<bool, IEnumerable<Report>>这样的东西,它包含两个元素,一个在上周有一个ReportDate的组和所有其他组。

FilteredList = lastWeekOrBefore[true].OrderBy(x => x.ReportDate)
       .Concat(lastWeekOrBefore[false].OrderByDescending(x => x.ReportDate))
       .ToList();

答案 1 :(得分:1)

试试这个:

var FilteredList = new List<DateTime>
{
    new DateTime(2017,3,3),
    new DateTime(2016,12,20),
    new DateTime(2017,3,5),
    new DateTime(2016,12,30),
    new DateTime(2017,3,4),
    new DateTime(2016,12,15)
};

var result = FilteredList.OrderByDescending(x => x > DateTime.Today.AddDays(-7)? 1 : 0)
    .ThenBy(x => x < DateTime.Today.AddDays(-7)
        ? -x.Ticks
        : x.Ticks);

foreach (var i in result)
    Console.WriteLine(i);

Console.ReadKey();

结果:

3/3/2017 12:00:00 AM
3/4/2017 12:00:00 AM
3/5/2017 12:00:00 AM
12/30/2016 12:00:00 AM
12/20/2016 12:00:00 AM
12/15/2016 12:00:00 AM