C# Linq List Contains Similar Elements
I am looking for linq query to see if there exists a similar object
I have an object graph as follows
开发者_StackOverflow社区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 the Cart => a CartProduct that has the exact same CartProductAttribute title values as a CartProduct that I need to compare. No more and no less.
E.G. I need to find a similar CartProduct that has a CartProductAttribute with title="red" and a cartProductAttribute with title="small" in myCart (eg '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 object graph
- myCart
- cartProduct1
- cpa1 (title=red)
- cpa2 (title=small)
- cartProduct2
- cpa3 (title=john)
- cpa4 (title=mary)
- cartProduct1
Linq query looking for
- cartProductToCompare
- cpa5 (title=red)
- cpa6 (title=small)
Should find
- cartProduct1
Hope all this makes sense...
Thanks
I think this is what you are after.
var attributes = new [] { "red", "small" };
var result = myCart.Products.Where(product =>
product.Attributes.All(attribute =>
attributes.Contains(attribute.title)
)
);
精彩评论