Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

query a sub-collection of a collection with linq

Tags:

c#

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!

like image 696
TheGeekYouNeed Avatar asked Jun 20 '10 00:06

TheGeekYouNeed


3 Answers

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.

like image 185
ckramer Avatar answered Sep 27 '22 23:09

ckramer


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)
                           );
like image 33
Thurein Avatar answered Sep 28 '22 01:09

Thurein


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)

like image 26
Tomas Petricek Avatar answered Sep 28 '22 01:09

Tomas Petricek