C # linear list contains similar items

I am looking for a linq query to see if a similar object exists

I have an object graph as follows

Cart myCart = new Cart { List<CartProduct> myCartProduct = new List<CartProduct> { CartProduct cartProduct1 = new CartProduct { List<CartProductAttribute> a = new List<CartProductAttribute> { CartProductAttribute cpa1 = new CartProductAttribute{ title="red" }, CartProductAttribute cpa2 = new CartProductAttribute{ title="small" } } } CartProduct cartProduct2 = new CartProduct { List<CartProductAttribute> d = new List<CartProductAttribute> { CartProductAttribute cpa3 = new CartProductAttribute{ title="john" }, CartProductAttribute cpa4 = new CartProductAttribute{ title="mary" } } } } } 

I would like to get from Cart => a CartProduct that has the same CartProductAttribute header values ​​as the CartProduct that I need to compare. No more and no less.

eg. I need to find a similar CartProduct with the CartProductAttribute attribute with title = "red" and the cartProductAttribute attribute with title = "small" in myCart (for example, "cartProduct1" in the example)

 CartProduct cartProductToCompare = new CartProduct { List<CartProductAttribute> cartProductToCompareAttributes = new List<CartProductAttribute> { CartProductAttribute cpa5 = new CartProductAttribute{ title="red" }, CartProductAttribute cpa6 = new CartProductAttribute{ title="small" } } } 

So, from the graph of objects

  • myCart
    • cartProduct1
      • cpa1 (title = red)
      • cpa2 (title = small)
    • cartProduct2
      • cpa3 (title = john)
      • cpa4 (title = mary)

Linq query is looking for

  • cartProductToCompare
    • cpa5 (title = red)
    • cpa6 (title = small)

Must find

  • cartProduct1

Hope this all makes sense ...

thanks

+4
source share
1 answer

I think this is what you need.

 var attributes = new [] { "red", "small" }; var result = myCart.Products.Where(product => product.Attributes.All(attribute => attributes.Contains(attribute.title) ) ); 
+5
source

Source: https://habr.com/ru/post/1307202/


All Articles