Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using List.Exists and Predicates correctly

Tags:

vb.net

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

like image 467
Dean Avatar asked Nov 28 '08 15:11

Dean


1 Answers

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.

like image 149
Barry Kelly Avatar answered Sep 27 '22 16:09

Barry Kelly