views:

2722

answers:

4
A: 

If you are using .net 3.5 this can be done with Linq to Objects:

http://msdn.microsoft.com/en-us/library/bb397937.aspx

If not, in 2.0 you can use Find method of the list:

http://msdn.microsoft.com/en-us/library/x0b5b5bc.aspx

The idea is that you will need to provide an method that return true if a property of your object satifies a certain condition.

Aleris
+1  A: 

Yes, this has everything to do with predicates :)

You want the Find(Of T) method. You need to pass in a predicate (which is a type of delegate in this case). How you construct that delegate depends on which version of VB you're using. If you're using VB9, you could use a lambda expression. (If you're using VB9 you might want to use LINQ instead of Find(Of T) in the first place, mind you.) The lambda expression form would be something like:

list.Find(function(c) c.ID = 1)

I'm not sure if VB8 supports anonymous methods in the same way that C# 2 does though. If you need to call this from VB8, I'll see what I can come up with. (I'm more of a C# person really :)

Jon Skeet
I am using VB9 On 2.0 and not 3.5 on this project :( I'll give the lambda expression a shot. Thanks!
Saif Khan
If you're using VB9 but restricted to .NET 2.0, you might want to look at LINQBridge: http://www.albahari.com/nutshell/linqbridge.aspx It's basically a LINQ to Objects implementation targeting .NET 2.0.
Jon Skeet
+3  A: 

Generally you need to use predicates:

list.Add(New Customer(1, "A"))
list.Add(New Customer(2, "B"))

Private Function HasID1(ByVal c As Customer) As Boolean
    Return (c.ID = 1)
End Function

Dim customerWithID1 As Customer = list.Find(AddressOf HasID1)

Or with inline methods:

Dim customerWithID1 As Customer = list.Find(Function(p) p.ID = 1)
Ozgur Ozcitak
A: 

You could also overload the equals method and then do a contains. like this

Dim list as new list(Of Customer)

list.Add(New Customer(1,"A")

list.Add(New Customer(2,"B")

list.contains(new customer(1,"A"))

the equals method then would look like this

public overrides function Equals(Obj as object) as Boolean
   return Me.Id.Equals(ctype(Obj,Customer).Id
end Function

Not tested but it should be close enough.

chrissie1