vb.net 正确使用 List.Exists 和 Predicates
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/325965/
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
Using List.Exists and Predicates correctly
提问by Dean
All
全部
I am currently trying implement something along the lines of
我目前正在尝试实现一些类似的东西
dim l_stuff as List(of Stuff)
dim m_stuff as new Stuff
m_stuff.property1 = 1
m_stuff.property2 = "This"
if not l_stuff.exists(m_stuff) then
l_stuff.add(m_stuff)
end if
This fails obviously as the Exist method is looking for a predicate of Stuff.
这显然失败了,因为 Exist 方法正在寻找 Stuff 的谓词。
Can anyone fully explain the predicate and how i can achieve what I am trying to do here.
任何人都可以完全解释谓词以及我如何实现我在这里尝试做的事情。
I have tried to use
我试过用
if not l_stuff.contains(m_stuff) then
l_stuff.add(m_stuff)
end if
however this doesn't detect the idenitcal entry and enters a duplicate into the list
但是这不会检测到相同的条目并在列表中输入重复项
Thank
谢谢
回答by Barry Kelly
List(Of T).Contains
is the method you should be using. Exists, as you say, expects a predicate. Of course, for .Contains to work as expected, you need to override the Equals()
method, as well as GetHashCode()
.
List(Of T).Contains
是您应该使用的方法。正如您所说,Exists 需要一个谓词。当然,要使 .Contains 按预期工作,您需要覆盖该Equals()
方法以及GetHashCode()
.
List(Of T).Exists
expects a function that will return a Boolean value when passed an item of type T, where T, in your case, is of type Stuff. So, you could write a method that looks like:
List(Of T).Exists
期望一个函数在传递 T 类型的项目时返回一个布尔值,其中 T 在您的情况下是 Stuff 类型。因此,您可以编写如下所示的方法:
If Not l_stuff.Exists(Function(x) x.property1 = m_stuff.property1 And _
x.property2 = m_stuff.property2) Then
and so on.
等等。