使用LINQ返回Collection中的元素,如果找不到元素,则返回Nothing

Cha*_*adD 1 linq vb.net

如果具有指定键的元素不在集合中,我希望以下函数返回Nothing.相反,它返回一个错误 - "没有找到元素"的效果

Public Class MyCollection

    Inherits System.Collections.ObjectModel.Collection(Of MyType)

    Public Function FindByActivityKey(ByVal searchValue As Integer) As MyType
        Return (From P In Me Order By P.ActivityPin.PrimaryKey = searchValue).First
    End Function

End Class
Run Code Online (Sandbox Code Playgroud)

建议?

Den*_*aub 8

更换First()FirstOrDefault()作为

Return (From P In Me Order By P.ActivityPin.PrimaryKey = searchValue) _
       .FirstOrDefault()
Run Code Online (Sandbox Code Playgroud)

First()假设至少有一个元素,如果找不到任何元素则抛出异常.默认FirstOrDefault()返回Nothing.