简体   繁体   中英

Linq query on 3rd child level

I have following requirement on List of objects. My class structure is like:

  public class Standard
    {
    public long Id {get;set;}
    public string Name {get;set;}
    public List<Student> Students {get;set;}
    }
    
    public class Student
    {
    public long Id {get;set;}
    public string Name {get;set;}
    public List<Hobby> Hobbies {get;set;}
    }
    
    public class Hobby
    {
    public long Id {get;set;}
    public string Name {get;set;}  
    }

I want to filter based on Hobbies on following scenarios:

  • List of All the Standards with Students who has hobby of Playing Music
  • List of All the Standards with Students who has hobby of Singing Songs

Currently I have List available with me with all child classes and details. I am able to do this with ForEach loop but wanted to learn Linq syntax for this scenarios.

Please suggest Linq syntax for this.

Given you have a collection of Standard called standards ,

List of All the Standards with Students who has hobby of Playing Music

var result = standards.Where(s => s.Students.Any(u => u.Hobbies.Any(h => h.Name == "Playing Music")));

List of All the Standards with Students who has hobby of Singing Songs

var result = standards.Where(s => s.Students.Any(u => u.Hobbies.Any(h => h.Name == "Playing Music")));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM