tags:

views:

82

answers:

1

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
+2  A: 

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
    }
}
Patrick Steele
I had the GroupBy and the foreach so far, but it was the nested froms that I hadn't tried. Thanks!
aponzani
+1 for managing to figure out the question. I used your answer to reverse-engineer what the question was :) . I've now updated the question so that it makes sense.
Mark Byers