【问题标题】:Get closest day in future in a LINQ expression在 LINQ 表达式中获取最近的一天
【发布时间】:2020-10-06 23:38:27
【问题描述】:

我在 yyyy/mm/dd 中有日期列表:

2020/06/10
2020/06/18
2020/07/17

和给定的日期

2020/06/10

我想在 LINQ 中找到距给定日期最近的一天(预期结果:2020/06/18)。

【问题讨论】:

  • "最早的一整天到给定日期"你能解释一下吗?你的意思是从给定日期起最近的一天?什么是一整天?
  • 是的,列表中最近的一天,通过说全天,我强调我想要 2020/06/18 而不是 2020/06/10。

标签: c# asp.net linq


【解决方案1】:

如果您的意思是在未来找到最接近的日期,那么您可以过滤掉所有较早的日期(包括相同的日期),对其进行排序,然后取第一个值:

List<DateTime> allDates = new List<System.DateTime>()
{
    new DateTime(2020, 06, 10),
    new DateTime(2020, 06, 18),
    new DateTime(2020, 07, 17),
};

DateTime givenDate = new DateTime(2020, 06, 10);

DateTime closestDateInFuture = allDates.Where(x => x > givenDate).OrderBy(x=> x).First();
Console.WriteLine(closestDateInFuture);

输出:

18.06.2020 00:00:00

@Johnathan Barclay 的另一个建议是使用Min 方法,它会产生相同的结果:

DateTime closestDateInFuture = allDates.Where(x => x > givenDate).Min()

【讨论】:

  • 甚至allDates.Where(x =&gt; x &gt; givenDate).Min()
  • @JohnathanBarclay 将其包含在我的回答中。如果您决定编写自己的答案,我将再次删除它:)
  • 我认为不需要单独回答 :)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-07-01
  • 2020-09-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多