简体   繁体   中英

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 list of assortments each containing a list of products (that are inside the assortment) and some other properties.

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

(translated from german into english)

I also tried something with RemoveAll or Where but I wasn't able to get it to work.

Using SelectMany you can get all products in any assortment

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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