【问题标题】:query a sub-collection of a collection with linq使用 linq 查询集合的子集合
【发布时间】:2010-06-20 00:54:14
【问题描述】:

我有一个产品集合,每个产品对象都有它自己的 ProductImages 集合。每个 ProductImage 对象都有一个 IsMainImage 布尔字段。我很难构建这样的 Linq 查询:

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

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

感谢您的帮助!

【问题讨论】:

    标签: c# linq


    【解决方案1】:

    试试类似的东西

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

    我还发现了101 linq queries 列表,其中可能包含对您有用的信息。

    【讨论】:

    • 我通常看那个页面——我可以在下面找到的示例名称是什么?非常感谢,当我被允许时会接受:)
    【解决方案2】:

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

            products.Where(product => product.productid == 1)
                    .SelectMany(product => 
                                            product.productimages.Where(image => image.ismainimage)
                                                                 .Select(image => image.imagename)
                               );
    

    【讨论】:

      【解决方案3】:

      另一种编写查询的方法是选择第一张图片,它是产品 1 的主图片:

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

      我认为这比嵌套的from 子句(通常用于连接和类似结构)更具可读性。使用First 也可能更有效,但这只是猜测(很可能无关紧要)

      【讨论】:

        猜你喜欢
        • 2011-10-05
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多