4

I have the following classes:

Product:

public class Product
{
    public string Name { get; set; }
    public List<Category> Categories { get; set; }
}

And Category:

public class Category
{
    public string Id { get; set; }
    public string Name { get; set; }
}

And I have the following method:

public List<Product> FilterProducts(List<Category> categories)
{
    // filtering code here
}

Question: How can I filter my products using a List<Categories> as parameter?

EDIT: One thing I forgot to mention is that if I have 2 categories I should be able to see only the products with the category1 AND category2. What I've done so far has returned only products with category1 OR category2. Although inherit IEquatable use Intersect seems interesting I am comparing with the Id's for now.

4

1 回答 1

12

如果您想返回包含所有提供的类别的所有产品,Categories这意味着它选择具有类别 1 和类别 2 的产品。

然后你需要使用All与 的组合Contains

public List<Product> FilterProducts(List<Category> categories)
{
    return products.Where(p => categories.All(c => p.Categories.Contains(c))
                   .ToList();
}

如果您想从提供的类别中返回至少一个类别的所有产品,这意味着它会选择具有类别 1 或类别 2 的产品。

然后你需要使用Any

public List<Product> FilterProducts(List<Category> categories)
{
    return products.Where(p => categories.Any(c => p.Categories.Contains(c)
                   .ToList();
}

请注意,如果您的对象与产品属性中的categories实例不同,或者您没有覆盖使用 s 的方法,您可能希望比较s 而不是类别对象本身。CategoriesCategoryEqualsIdId

所以像:

解决方案

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();
}
于 2013-07-06T17:49:01.940 回答