Thursday, April 28, 2011

Need help with a linq query please!

I am trying to write a query that will search for "orders" that contain a certain "product" and I'm having a little difficulty getting it to work. Basically, this is what I'm trying to do:

Dim orders = From o in db.Orders _
             Where o.OrderProducts.Contains(Function(p) p.ProductID = 123) _
             Select o

I've also tried with ...

Where o.OrderProducts.Where(Function(p) p.ProductID = 123)

but that doesn't work either. Where am I going wrong? Thanks!

From stackoverflow
  • Try using Any()

    Dim orders = From o in db.Orders _
                 Where o.OrderProducts.Any(Function(p) p.ProductID = 123) _
                 Select o
    
    Ryan : Thanks, that worked. I didn't know about the .Any() operator... What exactly does that do? I tried searching "linq to sql any" but any seems to be way too common of a word to get practical results back.
    shahkalpesh : http://www.hookedonlinq.com/AnyOperator.ashx
    Ryan Versaw : It functions exactly the same way you expected `Contains()` to. It will look for any item within the collection (o.OrderProducts in this case) that meets the condition provided. If it finds an item, it will short-circuit and return true, or it will keep looking until the end of the collection (and return false if it doesn't find an item).
    Ryan : awesome, thanks again!

0 comments:

Post a Comment