代码之家  ›  专栏  ›  技术社区  ›  TheGeekYouNeed

使用Linq查询集合的子集合

  •  13
  • TheGeekYouNeed  · 技术社区  · 15 年前

    我有一个产品集合,每个产品对象都有自己的ProductImages集合。每个ProductImage对象都有一个ismainimage bool字段。我很难构建这样的LINQ查询:

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

    有人能帮我解决这个问题吗?给我指出一个在线资源,在那里我可以学习如何编写这样的LINQ查询,或者两者兼而有之?

    谢谢你的帮助!

    3 回复  |  直到 15 年前
        1
  •  12
  •   ckramer    15 年前

    尝试一下

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

    我还找到了 101 linq queries 其中可能包含对您很好的信息。

        2
  •  5
  •   Thurein    15 年前

    也可以使用.selectmany()投影方法。

            products.Where(product => product.productid == 1)
                    .SelectMany(product => 
                                            product.productimages.Where(image => image.ismainimage)
                                                                 .Select(image => image.imagename)
                               );
    
        3
  •  3
  •   Tomas Petricek    15 年前

    编写查询的另一种方法是选择第一个图像,该图像是产品1的主图像:

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

    我认为这比嵌套的更可读 from 子句(通常用于联接和类似构造)。使用 First 也许效率更高,但这只是一个猜测(很可能不重要)