简体   繁体   English

LINQ / C# 从列表中删除多个其他列表中的所有项目

[英]LINQ / C# Remove all items from a list that are in multiple other lists

I have the following setup:我有以下设置:

  • 1 list containing about 500 products. 1 个包含大约 500 个产品的列表。

  • 1 list of assortments each containing a list of products (that are inside the assortment) and some other properties. 1 个分类列表,每个分类列表包含一个产品列表(在分类内)和一些其他属性。

My model looks like this (smiplified):我的模型看起来像这样(简化):

public Model() {
   public List<Products> {get; set;}
   public List<Assortment> {get; set;}
}

and the assortment looks like this (simplified)和分类看起来像这样(简化)

public Assortment() {
   public int ID {get; set;}
   public string Name {get; set;}
   public List<Product> Products {get; set;
}

I would like to display all products that are NOT in any assortment .我想展示不属于任何分类的所有产品

I tried something like this:我试过这样的事情:

Model.Products.Except(x => Model.Assortments.Where(y => y.Products.Contains(x)).Select(z => z.Products).ToList()

But the compiler tells me但是编译器告诉我

"Lambdaexpression" cannot be converted into type "IEnumerable" because it's no delegate type “Lambdaexpression”不能转换为“IEnumerable”类型,因为它不是委托类型

(translated from german into english) (从德文翻译成英文)

I also tried something with RemoveAll or Where but I wasn't able to get it to work.我还尝试了使用 RemoveAll 或 Where 的方法,但无法使其正常工作。

Using SelectMany you can get all products in any assortment使用 SelectMany,您可以获得任何分类中的所有产品

Model.Assortments.SelectMany(a => a.Products)

so the products which are not in any assortment are:所以不属于任何分类的产品是:

Model.Products.Except(Model.Assortments.SelectMany(a => a.Products))

As @GuruStron noted in a comment, this assumes that the products in the assortments can be identified with the products the Products collection either because they are the same object or by a suitable Equals override.正如@GuruStron 在评论中指出的那样,这假设分类中的产品可以与 Products 集合中的产品标识,因为它们是相同的对象或通过合适的Equals覆盖。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM