订购 NodaTime Nullable OffsetDateTime

问题描述

我有一个包含可为空的 NodaTime.OffsetDateTime 属性的类约会。如果我有一个约会列表,我将如何使用 Linq OrderBy 先用空值 StartDateTime 然后按降序对 StartDateTime 进行排序?

Class Appointment
{
    public OffsetDateTime? StartDateTime { get; set; }
}

我试过这样做

var orderedAppointments = myAppointmentsList
    .OrderByDescending(x => x.StartDateTime is null)
    .ThenByDescending(x => x.StartDateTime,OffsetDateTime.Comparer.Local)
    .ToList();

但我收到一个错误,因为 OffsetDateTime.Comparer 无法处理空值。

我可以做这样的事情

var orderedAppointments = myAppointmentsList
    .OrderByDescending(x => x.StartDateTime ?? StartDateTime.MaxValue,OffsetDateTime.Comparer.Local)
    .ToList();

StartDateTime 没有 MaxValue

这里的建议是什么,创建我自己的 OffsetDateTime 最大值,或者是否有我缺少的更好的方法

解决方法

所以你首先想要空值?然后你可以使用:

var orderedAppointments = myAppointmentsList
    .OrderBy(x => x.StartDateTime.HasValue ? 1 : 0)
    .ThenByDescending(x => x.StartDateTime.GetValueOrDefault(),OffsetDateTime.Comparer.Local)
    .ToList();