[英]Select items from a List where the children contain the items from another List using LINQ
我有以下课程:
产品:
public class Product
{
public string Name { get; set; }
public List<Category> Categories { get; set; }
}
和类别:
public class Category
{
public string Id { get; set; }
public string Name { get; set; }
}
我有以下方法:
public List<Product> FilterProducts(List<Category> categories)
{
// filtering code here
}
问题:如何使用List<Categories>
作为参数过滤我的产品?
编辑:我忘了提到的一件事是,如果我有2个类别,我应该只能看到类别1 和 类别2的产品。 到目前为止我所做的只返回了category1 OR category2的产品。 虽然继承IEquatable使用Intersect似乎很有趣,但我现在正在与Id进行比较。
如果要返回其Categories
包含所有提供的类别的所有产品,这意味着它选择具有category1和category2的产品。
然后你需要使用All
with Contains
的组合:
public List<Product> FilterProducts(List<Category> categories)
{
return products.Where(p => categories.All(c => p.Categories.Contains(c))
.ToList();
}
如果您想从所提供的类别中返回所有产品中的至少一个产品,这意味着它选择具有category1或category2的产品。
然后你需要使用Any
public List<Product> FilterProducts(List<Category> categories)
{
return products.Where(p => categories.Any(c => p.Categories.Contains(c)
.ToList();
}
请没有,如果你的categories
对象不是你在有相同的情况下, Categories
产品的性能或在您的Category
你不重写Equals
方法使用该Id
,你可能要比较的Id
而不是类对象第他们自己。
所以类似于:
所有的解决方案
public List<Product> FilterProducts(List<Category> categories)
{
return products.Where(p => categories
.All(c => p.Categories.Any(cat => cat.Id == c.Id)).ToList()
}
任何解决方案
public List<Product> FilterProducts(List<Category> categories)
{
return products.Where(p => categories
.Any(cat => p.Categories.Any(pcat => pcat.Id == cat.Id)).ToList();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.