vb.net - FirstOrDefault(Of Time) 当我真的想要 "FirstOrNothing"vb.net

标签 vb.net linq

在 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 是值类型,不能为 nothingFirstOrDefault 不能返回 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/

相关文章:

c# - 时钟速度公式

asp.net - .Net 中的后台处理 - 需要建议

vb.net - 字节转换回图像

c# - Linq to SQL、SQL Server 2008 和优化

c# - 在导航属性 Entity Framework 上正确使用接口(interface)

c# - 使用 PLINQ 是否有可能提高效率?

c# - 使用 Sitecore 8 内容搜索 API 的复杂查询

java - 如何通过 soap 网络服务 (XML) 传递图像的字节数组并在 Android 设备上解码此字节数组以将其转换回图像

c# - XPath:选择所有A节点和不在A节点内的所有B节点

c# - 使用 Linq 过滤 ComboBox.DataSource?