Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

List.Contains based on a property of a list item

I have a List myList of MyObjects. Is it possible to check if myList contains a particular myObject based on a property of myObject in VB.NET? In C#, you'd something similar to this right:

myList.Exists(myObject => myObject.property1 == 3)
like image 858
Prabhu Avatar asked Jan 11 '11 20:01

Prabhu


2 Answers

I'm sure you could use myList.Exists in VB.NET too, just with its lambda expression syntax.

However, the more general way is to use the Any LINQ operator, with the overload that takes a predicate. For example:

myList.Any(Function(myObject) myObject.property1 = 3)

Personally I prefer to use LINQ operators unless the more specific List<T> method provides a significant advantage for some reason.

EDIT:

If you need to access the object afterwards, just use:

Dim foo = myList.FirstOrDefault(Function(myObject) myObject.property1 = 3)
If (foo Is Not Nothing) Then
    ...
End If
like image 82
Jon Skeet Avatar answered Dec 09 '22 03:12

Jon Skeet


It's roughly the same, except VB.NET has a different syntax for lambda expressions:

myList.Exists(Function(myObject) myObject.property1 = 3)
like image 41
Thomas Levesque Avatar answered Dec 09 '22 02:12

Thomas Levesque