TheGeekYouNeed
TheGeekYouNeed

Reputation: 7539

query a sub-collection of a collection with linq

I've got a collection of products, and each product object has it's own ProductImages collection. Each ProductImage object has a IsMainImage bool field. I'm having a hard time building a Linq query like this:

select products.productimages.imagename where products.productid == 1 and     
product.productimages.ismainimage == true

Can anyone help me figure this out, point me to an online resource where I can learn about writing linq queries like this, or both?

Thank you for your help!

Upvotes: 17

Views: 13676

Answers (3)

Thurein
Thurein

Reputation: 2566

You can also use .SelectMany() projection method also.

        products.Where(product => product.productid == 1)
                .SelectMany(product => 
                                        product.productimages.Where(image => image.ismainimage)
                                                             .Select(image => image.imagename)
                           );

Upvotes: 7

Tomas Petricek
Tomas Petricek

Reputation: 243041

Another way to write the query is to select first image that is the main image for the product 1:

var q = from p in products 
        where p.ProductID == 1 
        select p.ProductImages.First(img => img.IsMainImage);

I would think this is more readable than nested from clauses (which are usually used for joins and similar constructs). Using First may be also more efficient, but that's just a guess (and it very likely doesn't matter)

Upvotes: 3

ckramer
ckramer

Reputation: 9443

Try something like

from product in products
where product.productid == 1
from image in product.productimages
where image.ismainimage
select image.imagename

I also found this list of 101 linq queries which may contain good information for you.

Upvotes: 13

Related Questions