在 linq 中,我尝试根据一组条件返回日期,或者如果没有值,我想返回Nothing
。如果值为 null (1-1-0001 12:00:00AM),则 FirstOrDefault()
返回默认日期,这意味着其上的 .HasValue
将返回 true。
如果我使用 First()
,它会抛出 System.NotSupportedException
并建议我使用 FirstOrDefault()
。
.Property = table.LinkedTableName.Where(Function(r) r.statusId = desiredStatusId) _
.Select(Function(r) r.Date) _
.OrderBy(Function(r) table.Date).FirstOrDefault()
这一切都在 Select New DataObject() With {}
我找到了custom extension关于它:
<System.Runtime.CompilerServices.Extension()>
Public Function FirstOrNothing(Of T As Structure)(source As IEnumerable(Of T), _
match As Func(Of T, Boolean)) As Nullable(Of T)
For Each item In source
If match(item) Then
Return item
End If
Next
Return Nothing
End Function
我很想知道是否有任何内置方法或更简单的方法来处理这个问题。提前致谢。
最佳答案
由于 DateTime
是值类型,不能为 nothing
,FirstOrDefault
不能返回 nothing
。但是,您可以在执行 FirstOrDefault
DateTime
(Function(r) Directcast(table.Date, DateTime?)).FirstOrDefault()
关于vb.net - FirstOrDefault(Of Time) 当我真的想要 "FirstOrNothing"vb.net,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31612428/