在F#中,如何对Nullable属性进行排序?

f#

我有一个从数据库下载的数组,其中的属性 service_time 是Nullable<DateTime>

service_time: Nullable<DateTime>

在 F# 中,如何对这个数组进行排序,将 service_time = null 的所有元素放在新数组的最前面?

Array.sortBy (fun t -> t.service_time)

给出:“Nullable”类型不支持“比较”约束。

回答

您可以利用default(DateTime)等于DateTime.MinValue和排序的事实,service_time.GetValueOrDefault()如下所示:

Array.sortBy (fun t -> t.service_time.GetValueOrDefault())

或者,更明确地说:

Array.sortBy (fun t -> t.service_time.GetValueOrDefault(DateTime.MinValue))

如果你想把空值放在数组的末尾,你可以这样做:

Array.sortBy (fun t -> t.service_time.GetValueOrDefault(DateTime.MaxValue))

演示小提琴在这里。


以上是在F#中,如何对Nullable属性进行排序?的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>