Removing items in a list of list

Let's say I have a class named Inventory. Inventory has many Products. Each Products has many characteristics like Size or a list of Colors.

I want to remove all the Colors of my Hats in the inventory. I was wondering if it is possible within 1 line using LINQ instead of using a loop.

inventory.Products.Where(x=>x.name.ToLower() == "hats").SelectMany(x=> x.Colors) 

This is as much as I could get for now.

Thanks !

Upvotes: 0

Views: 63

Answers (1)

Camilo Terevinto
Camilo Terevinto

Reputation: 32068

If you so much want a one-liner, you should use this:

foreach (var product in inventory.Products.Where(x => x.name.ToLower() == "hats")) { product.Colors.Clear(); }

LINQ is a library for querying data, not for altering it. Balancing LINQ and language features here is much better than going "one line LINQ only" for no reason.

Upvotes: 3

Related Questions