【问题标题】:Getting distinct not null dates from datetime collection从日期时间集合中获取不同的非空日期
【发布时间】:2015-06-08 15:00:20
【问题描述】:

我有一个这样的日期时间集合:

IEnumerable<DateTime?> dates

我想按降序获取不同日期的集合

   IEnumerable<DateTime> dtCollection = dates.Where(x => x.HasValue).Distinct().OrderByDescending(x => x).AsEnumerable();

在上面的代码中,我得到了无效转换的异常,并且 distinct 返回不同的(日期+时间)而不是不同的日期。

所以:

  1. 为什么Where(x =&gt; x.HasValue) 没有丢弃所有空值
  2. 如何修复我的代码以完成任务?

谢谢,

【问题讨论】:

  • @GrantWinney 我想忽略时间我只需要不同的日期
  • 对于您的1,因为没有人回答它:仅仅因为您使用HasValue,您实际上并没有将您的DateTime? 转换为DateTime。它只是抓取所有不为空的项目。因此,您需要从这些项目中获取Value,如这些答案所示。

标签: c# .net linq collections lambda


【解决方案1】:

您可以使用 .Date 来获取 DateTime 的日期组件,因此:

dates
    .Where(x => x.HasValue)
    .Select(x => x.Value.Date)
    .Distinct()
    .OrderByDescending(x => x)

回答您的第一点,Where(x =&gt; x.HasValue) 如您所愿丢弃所有空值,但您仍然留下DateTime? 的集合而不是DateTime ,当你尝试将它分配给你的IEnumerable&lt;DateTime&gt; dtCollection 时会导致类型转换错误,因此你需要使用x.Value 将每个DateTime? 转换为DateTime

【讨论】:

    【解决方案2】:

    在查询中,通过选择 DateTime? 对象的值将其转换为 DateTime

    IEnumerable<DateTime> dtCollection = dates
        .Where(x => x.HasValue)
        .Select(x => x.Value)
        .Distinct()
        .OrderByDescending(x => x)
        .AsEnumerable();
    

    由于Where() 子句只过滤那些有值的子句,Select() 子句应该成功而不会出错。然后 Select() 的输出是 DateTime 的集合,而不是 DateTime?

    相反,要仅选择DateTime 中的一个属性,请更新该子句:

    .Select(x => x.Value.Date)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-01-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-26
      • 1970-01-01
      相关资源
      最近更新 更多