List(Of T).Find()在找不到值时不起作用,循环更好?

时间:2014-12-31 18:42:15

标签: vb.net lambda nullreferenceexception

我将不得不离开Find(),.FirstOrDefault()等,并用循环替换它,除非有人可以解释如何处理不会返回值的列表?

Public Class Form1

    Public Class TestClass
        Public Property item1 As String
        Public Property item2 As String
    End Class

    Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
        Dim myLst As New List(Of TestClass)
        myLst.Add(New TestClass With {.item1 = "A", .item2 = "B"})
        myLst.Add(New TestClass With {.item1 = "C", .item2 = "D"})

        Debug.WriteLine(myLst.Find(Function(n) n.item1 = "X").item1) ' nullreferenceexception, what?

    End Sub

End Class

1 个答案:

答案 0 :(得分:5)

您只需处理FindFirstOrDefault不返回任何内容的情况。如果没有返回任何内容,则访问item1属性,这会导致NullReferenceException。

Public Sub Button2_Click(sender As Object, e As EventArgs)
    Dim myLst As New List(Of TestClass)
    myLst.Add(New TestClass With {.item1 = "A", .item2 = "B"})
    myLst.Add(New TestClass With {.item1 = "C", .item2 = "D"})

    Dim tryFindItem = myLst.Find(Function(n) n.item1 = "X")
    If tryFindItem IsNot Nothing Then
        Debug.WriteLine(tryFindItem.item1)
    Else
        Debug.WriteLine("Nothing was found!")
    End If
End Sub