开发者

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


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

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜