VB.NET LINQ 查询列表(对象)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/22308608/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
VB.NET LINQ query on List(Of Object)
提问by Moojjoo
I am having trouble with a LINQ query -
我在使用 LINQ 查询时遇到问题 -
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()
ErrorAn exception of type 'System.NullReferenceException' occurred in CI.dll but was not handled in user code
错误'System.NullReferenceException' 类型的异常发生在 CI.dll 中,但未在用户代码中处理
Additional information: Object reference not set to an instance of an object.
附加信息:未将对象引用设置为对象的实例。
The problem is the listOfcontains the value "Nothing" for the x.Codes.Contains.
问题是listOf包含x.Codes.Contains的值“Nothing”。
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.
我只需要能够返回具有匹配 ID_NUM 和代码的记录。
回答by Steven Doggart
You need to check if it's Nothingfirst and use the AndAlsokeyword to stop it from evaluating the latter statement. AndAlsois short-circuiting. See this linkfor more information on what that means.
您需要检查它是否是Nothing第一个并使用AndAlso关键字来阻止它评估后一个语句。 AndAlso是短路。有关这意味着什么的更多信息,请参阅此链接。
Also, when checking if an object is null, you should use the Isor IsNotoperator rather than =. From this MSDN article:
此外,在检查对象是否为空时,您应该使用IsorIsNot运算符而不是=。来自这篇 MSDN 文章:
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.
检查引用(或可为空值类型)变量是否为空时,不要使用 = Nothing 或 <> Nothing。始终使用 Is Nothing 或 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()

