Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

LINQ Where statement in collection

Tags:

vb.net

linq

I have a Customer object which has a collection of ContactNumbers. Is it possible with LINQ to get a list of Customers where one of the contact numbers = '123'?

Public Class Customer
    Public Overridable Property ContactNumbers As List(Of ContactNumber)

End Class

Public Class ContactNumber

    <Required()>
    Public Property ID As Integer

    <Required()>
    <StringLength(20)>
    Public Property Number As String

    Public Overridable Property Type As ContactNumberType

    Public Property Primary As Boolean

End Class


Dim findnumber as String = '123'
Dim customers = db.customers.tolist

customers = customers.Where..... ?
like image 627
Tom Avatar asked Feb 21 '23 00:02

Tom


1 Answers

Try the following

customers = customers.Where(Function (x) x.ContactNumbers.Any(Function (y) y.Number = "123"))

The trick here is the Any function. This will return True if any of the items in the collection match the predicate. In this case y.Number = 123

like image 162
JaredPar Avatar answered Feb 27 '23 04:02

JaredPar