tags:

views:

89

answers:

3

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!

A: 

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.

ckramer
I usually look at that page -- what is the name of the example on there that I can find this under? thanks so much, will accept when I'm allowed :)
TheGeekYouNeed
+1  A: 

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)

Tomas Petricek
A: 

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)
                           );
Kthurein