JTunney
JTunney

Reputation: 904

Check if object exists in a VB.NET dictionary using Primary Key

I have a dictionary declared like this:

Dim customersDictionary As Dictionary(Of Customer, IList(Of String))

A Customer object is the key and for each customer object there is list of String values.

How would I return a bool checking to see if a customer with an id of 123 exists in the dictionary?

Upvotes: 1

Views: 2697

Answers (1)

Steve
Steve

Reputation: 216253

If you are just interested to know if a customer with the specified ID exists in your dictionary then you could write

dim result  = custList.Any(Function(x) x.Key.ID = 123)
if result then
    Console.WriteLine("Customer with ID=123 exists")
End if

Instead if you want to retrieve the customer given the ID then

dim result  = custList.Where(Function(x) x.Key.ID = 123).FirstOrDefault()
if result.Key IsNot Nothing Then
    Dim cust = result.Key
    Console.WriteLine("Customer Name is = " & cust.Name) ' or whatever property of your customer
End If

Upvotes: 2

Related Questions