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!
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.
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)
);
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With