开发者

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)

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)
    )
);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜