C# Linq List Contains Similar Elements

Posted by John Peters on Stack Overflow See other posts from Stack Overflow or by John Peters
Published on 2010-04-17T00:49:47Z Indexed on 2010/04/17 0:53 UTC
Read the original article Hit count: 674

Filed under:
|

Hi All,

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

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 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

© Stack Overflow or respective owner

Related posts about c#

Related posts about LINQ