11

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.

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

Dean
  • 5,800
  • 11
  • 54
  • 94

1 Answers1

25

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).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:

If Not l_stuff.Exists(Function(x) x.property1 = m_stuff.property1 And _
x.property2 = m_stuff.property2) Then

and so on.

Siddharth Rout
  • 137,434
  • 15
  • 189
  • 237
Barry Kelly
  • 39,856
  • 4
  • 99
  • 180