使用LINQ返回Collection中的元素,如果找不到元素则不返回Nothing
如果具有指定键的元素不在集合中,我希望以下函数返回 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
建议?
I would like the following function to return Nothing if the element with the specified key is not in the collection. Instead, it returns an error - something to the effect of "no element found"
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
Suggestions?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
将
First()
替换为FirstOrDefault()
,如First()
假设至少有一个元素,如果不能,则抛出异常找到任何。默认情况下,FirstOrDefault()
返回Nothing
。Replace
First()
withFirstOrDefault()
as inFirst()
assumes there is at least one element and throws an exception if it can't find any.FirstOrDefault()
returnsNothing
by default.