If you ever need to project a result set or find a single object in a generic list then one of the easiest ways to achieve this is to use a lambda expression within either the FIND() or FINDALL() extension methods for the generic list class.

For example, suppose we have the following class that represents a person.


Public Class Person
Property FirstName As String
Property Surname As String
Property DateOfBirth As Date
Property Gender As String
Public Overrides Function ToString() As String
Return FirstName & " " & Surname
End Function
End Class

This is a nice simple class with two property that represent the first name and surname of a person. Next we create a generic list of type person and then add some records to it as the below example

Dim PersonList As New List(Of Person)
PersonList.Add(New Person With {.FirstName = "Bob", .Surname = "Smith"})
PersonList.Add(New Person With {.FirstName = "Fred", .Surname = "Jones"})
PersonList.Add(New Person With {.FirstName = "John", .Surname = "Bond"})
PersonList.Add(New Person With {.FirstName = "Peter", .Surname = "Smith"})

Now that we have some data to search we can create a ‘for each’ loop to enumerate the list and we will call the extension method FINDALL() so that we can project which records go into the ‘for each’ loop. The filtering within the FINDALL() extension is done via a lambda expression which is nice and simple.

For Each p In PersonList.FindAll(Function(x) x.Surname = "Smith")

If we only want to find a single value in the collection then we could use the FIND() extension in much the same way as the above example, the FIND() extension will return the first occurrence that it finds of the filter criteria.

Dim SinglePerson = PersonList.Find(Function(x) x.FirstName = "Bob" And x.Surname = "Smith")
Console.WriteLine("Single Person: " & SinglePerson.FirstName)

If you need a more complex filter method then this is probably where you would start needing to look at LINQ which just makes complex queries a whole lot simpler.

Categories: VB.NET

Leave a Reply

Your email address will not be published. Required fields are marked *