aponzani
aponzani

Reputation: 438

How can I use LINQ to find the Intersect between two properties of the same collection?

Given an IList<Foo> with a data set that looks like this:

ID   CHILD  PARENT TYPE  
1   102    101    UPSELL  
1   103    101    UPSELL  
2   102    101    BONUS  
2   104    103    BONUS  
3   102    101    BONUS  
4   102    101    PRODUCT  
4   104    102    PRODUCT  

How can I use LINQ to find a child which has a parent with the same ID?

Desired output is

ID   CHILD  PARENT TYPE 
4   102    101    PRODUCT

Upvotes: 1

Views: 611

Answers (1)

PatrickSteele
PatrickSteele

Reputation: 14677

I think this is what you're looking for. I grouped by ID first so I could process each group individually, but there's probably a way to combine it into a single query.

var grouping = foos.GroupBy(f => f.ID);
foreach(var g in grouping)
{
    var result = (from f1 in g from f2 in g where f1.Child == f2.Parent select f1);
    if( result.Any())
    {
        // you have your answer
    }
}

Upvotes: 3

Related Questions