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.

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

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.


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x