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

use*_*035 2 .net c# 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 ? 
    } 
} 
Run Code Online (Sandbox Code Playgroud)

Ser*_*kiy 6

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

如果你只需要grandChildren收集那些收藏的大孩子:

grandChildren.Intersect(
    perons.SelectMany(p => p.Children)
          .SelectMany(c => c.GrandChildren));
Run Code Online (Sandbox Code Playgroud)

  • 性能将是残酷的,因为您必须加载P*C*G条目,尽管只要您尝试使用ORM进行此类查询,这是不可避免的 (2认同)