使用linq查询集合的子集合

The*_*eed 14 c# linq

我有一系列产品,每个产品对象都有自己的ProductImages集合.每个ProductImage对象都有一个IsMainImage bool字段.我很难建立像这样的Linq查询:

select products.productimages.imagename where products.productid == 1 and     
product.productimages.ismainimage == true
Run Code Online (Sandbox Code Playgroud)

任何人都可以帮我解决这个问题,请指出一个在线资源,我可以学习如何编写这样的linq查询,或两者兼而有之?

谢谢您的帮助!

ckr*_*mer 12

尝试类似的东西

from product in products
where product.productid == 1
from image in product.productimages
where image.ismainimage
select image.imagename
Run Code Online (Sandbox Code Playgroud)

我还找到了101个linq查询列表,其中可能包含很好的信息.


Kya*_*ein 5

您也可以使用.SelectMany()投影方法.

        products.Where(product => product.productid == 1)
                .SelectMany(product => 
                                        product.productimages.Where(image => image.ismainimage)
                                                             .Select(image => image.imagename)
                           );
Run Code Online (Sandbox Code Playgroud)