Reputation: 753
I am having trouble with a LINQ query -
Dim otherRecords As List(Of Objects) = listOf.Where(Function(x) x.ID_NUM = newID _
And (x.Codes.Contains(ddlPrimaryCode.SelectedItem.Text.Trim) And Not x.Codes = Nothing)).ToList()
Error An exception of type 'System.NullReferenceException' occurred in CI.dll but was not handled in user code
Additional information: Object reference not set to an instance of an object.
The problem is the listOf contains the value "Nothing" for the x.Codes.Contains.
Before I had
Dim otherRecords As List(Of Objects) = listOf.Where(Function(x) x.ID_NUM = newID _
And (x.Codes.Contains(ddlPrimaryCode.SelectedItem.Text.Trim)).ToList()
And it was crapping out.
I need to be able to return only records with matching ID_NUM and Codes.
Upvotes: 5
Views: 29088
Reputation: 43743
You need to check if it's Nothing
first and use the AndAlso
keyword to stop it from evaluating the latter statement. AndAlso
is short-circuiting. See this link for more information on what that means.
Also, when checking if an object is null, you should use the Is
or IsNot
operator rather than =
. From this MSDN article:
When checking whether a reference (or nullable value type) variable is null, do not use = Nothing or <> Nothing. Always use Is Nothing or IsNot Nothing.
This should work
Dim otherRecords As List(Of Objects) = listOf.Where(Function(x) _
(x.ID_NUM = newID) AndAlso _
(x.Codes IsNot Nothing) AndAlso _
(x.Codes.Contains(ddlPrimaryCode.SelectedItem.Text.Trim()))).ToList()
Upvotes: 7