从日期时间集合中获取不同的非空日期

Getting distinct not null dates from datetime collection

我有一组这样的日期时间:

IEnumerable<DateTime?> dates

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

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

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

所以 :

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

谢谢,

在查询中,通过 selecting 对象的值将 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 一个 属性,更新该子句:

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

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

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

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