如何从一个人的名单中查询大孩子?

时间:2013-11-25 09:55:54

标签: c# .net linq entity-framework iqueryable

下面在这段代码中,我已经解释了我想要的内容,请有人帮我解决这个问题。

public class Person
{
    public IEnumerable<Child> Children { get; set; } 
}

public class Child
{
    public IEnumerable<GrandChild> GrandChildren { get; set; } 
} 

public class SearchingClass
{
    public void Search()
    {
        IEnumerable<Person> persons = MyPersons;
        IEnumerable<GrandChild> grandChildren = MyGrandChildren

        //Now I want only the Grand Children who are grand children of persons in Persons List 
        //How can I write a query for this ? 
    } 
} 

1 个答案:

答案 0 :(得分:6)

perons.SelectMany(p => p.Children)
      .SelectMany(c => c.GrandChildren); 
      // add Distinct() if you need distinct results

如果您只需要获得grandChildren集合中的大孩子:

grandChildren.Intersect(
    perons.SelectMany(p => p.Children)
          .SelectMany(c => c.GrandChildren));