Linq查询以过滤多级类

时间:2019-08-23 13:19:27

标签: c# linq

我的部门数据来自数据库。我想根据某些条件过滤此数据。

[  
   {  
      "Id":10,
      "Name":"Name 10",
      "Teachers":[  
         {  
            "TeacherId":100,
            "TeacherName":null,
            "DepartmentId":100,
            "Students":[  
               {  
                  "StudentId":1001,
                  "StudentName":null,
                  "TeacherId":10,
                  "DepartmentId":100
               }
            ]
         },
         {  
            "TeacherId":101,
            "TeacherName":null,
            "DepartmentId":100,
            "Students":[  
               {  
                  "StudentId":1001,
                  "StudentName":null,
                  "TeacherId":10,
                  "DepartmentId":100
               }
            ]
         }
      ]
   },
   {  
      "Id":100,
      "Name":"Name 10",
      "Teachers":[  
         {  
            "TeacherId":0,
            "TeacherName":null,
            "DepartmentId":100,
            "Students":[  
               {  
                  "StudentId":5000,
                  "StudentName":null,
                  "TeacherId":50,
                  "DepartmentId":100
               }
            ]
         }
      ]
   },
   {  
      "Id":50,
      "Name":"Name 10",
      "Teachers":[  
         {  
            "TeacherId":0,
            "TeacherName":null,
            "DepartmentId":100,
            "Students":[  
               {  
                  "StudentId":2000,
                  "StudentName":null,
                  "TeacherId":50,
                  "DepartmentId":100
               }
            ]
         }
      ]
   }
]

现在我必须根据如下所示的一些值来过滤部门

var departmenIds = new List<int>() { 10, 20, 30 };
var teachers = new List<int>() { 100, 200, 300 };
var students = new List<int>() { 1000, 2000, 3000 };

我正在寻找一个查询,该查询将以以下方式返回数据

如果json中存在所有部门ID,它将返回整个数据。如果列表中有一个具有特定老师的部门,则仅返回该老师和该部门。对学生来说是明智的。

我尝试过此方法来测试它是否至少在第二级上起作用,但是我得到了所有的老师

var list = allDeplrtments.Where(d => d.Teachers.Any(t => teachers.Contains(t.TeacherId))).ToList();

1 个答案:

答案 0 :(得分:1)

var list = allDepartments
    .Where(d => departmentIds.Contains(d.Id))
    .Select(d => new Department() {
        Id = d.Id,
        Name = d.Name,
        Teachers = (d.Teachers.Any(t => teacherIds.Contains(t.TeacherId))
            ? d.Teachers.Where(t => teacherIds.Contains(t.TeacherId))
            : d.Teachers)
                .Select(t => new Teacher() {
                    TeacherId = t.TeacherId,
                    TeacherName = t.TeacherName,
                    DepartmentId = d.Id,
                    Students = t.Students.Any(s => studentIds.Contains(s.StudentId))
                        ? t.Students.Where(s => studentIds.Contains(s.StudentId))
                        : t.Students
                })
    })

这样对您有用吗?