【问题标题】:Filter on child collection using LINQ使用 LINQ 过滤子集合
【发布时间】:2017-05-23 02:37:29
【问题描述】:

我有这两个模型(多对多关系):

public class Product
{
    public int ProductId { get; set; }
    public string Name { get; set; }

    #region Navigation properties 
    public List<Category> Categories { get; set; }
    #endregion
}

public class Category
{
    public int CategoryId { get; set; }
    public string Name { get; set; }

    #region Navigation properties
    public List<Product> Products { get; set; }
    #endregion
}

那我有这个动作方法:

[HttpPost]
public async Task<ActionResult> FilterProducts(List<int> categoryIds)
{
    var productsViewModel = new ProductsViewModel();

    if (categoryIds != null)
    {
        var products = await db.Products
                   .AsNoTracking()
                   .Where(??????????????????????)
                   .Where(p => p.Visible == true)
                   .OrderBy(p => p.Importance)
                   .ToListAsync();

        productsViewModel.Products = products;
    }
    else { // Do something else }

    return PartialView("_ProductsPartial", productsViewModel);
}

我想做的是使用 LINQ(.Where(??????))通过categoryIds 获取所有产品。所以每个产品都有一个类别列表。我只想获取包含categoryIds 的产品。

不太确定如何构造 LINQ 查询,因为过滤是在子集合上完成的。有什么想法吗?

【问题讨论】:

  • 那么你需要得到哪些品类相同的产品?或者至少有一个 categoryIds 的类别?
  • 至少一个类别。
  • 我会采取另一条路线并获取指定类别的产品。换句话说,查询类别及其产品。
  • 其实我想我会需要这两种情况。至少一个类别。以及拥有所有类别的产品。

标签: c# linq


【解决方案1】:

这将返回所有Products,其中至少有一个来自categoryIds 的类别

.Where(x => x.Categories.Any(y => categoryIds.Contains(y.CategoryId)));

【讨论】:

    【解决方案2】:

    这将返回具有 all categoryIds

    的产品
    Where(p => categoryIds.
             Intersect(p.Categories.Select(ctgry => ctgry.CategoryId)).
             Count() == categoryIds.Count())
    

    (假设 categoryIds 有唯一的元素,List Categories 的元素有唯一的 CategoryId 字段)

    【讨论】:

    • 我不理解 .Count() == categoryIds.Count()?这种情况有什么用?
    • 'intersect' 部分查找在 categoryIds 中也可以找到的给定产品的类别 ID。然后,如果这些 (.Count()) 的数量等于 categoryIds (categoryIds.Count()) 的大小,我们知道 categoryIds 中的所有项目都在给定的 Product 中找到。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-26
    • 1970-01-01
    • 2011-04-21
    • 2012-04-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多