Linq Where然后在HashSet上选择

本文关键字:选择 HashSet Where 然后 Linq | 更新日期: 2023-09-27 18:16:03

我试图获得与某个类别id匹配的产品列表。我遇到的问题是,我在where之前使用select子句,基本上是试图过滤,一旦我已经得到了所有的结果。通常它是直接的,但由于这个导航属性是一个HashSet,它被证明更棘手。我的repo.GetAll()从数据库中获取所有产品。CategoryProducts是产品和类别之间的链接表,它也是产品表上的导航属性

ProductRepository repo = new ProductRepository();
var products = 
   repo.GetAll()
       .Select(c => c.CategoryProducts
                     .Where(p => p.CategoryId == 35));

以上只是返回我所有的产品,任何帮助是感激的。

Linq Where然后在HashSet上选择

您的查询返回一个与您的所有产品对应的可枚举对象,该可枚举对象中的每一项本身也是一个可枚举对象,包含0个或多个ID为35的类别。

你可以修改你的查询,只获取类别为35的产品:

var products = repo
    .GetAll()
    .Where(p => p.CategoryProducts.Any(c => c.CategoryId == 35));