[英]Linq query to filter multi level classes
I have my departments data coming from the database. 我的部门数据来自数据库。 I want to filter this data based on certain criteria. 我想根据某些条件过滤此数据。
[
{
"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
}
]
}
]
}
]
Now I have to filter the departments based on some values as shown below 现在我必须根据一些值来过滤部门,如下所示
var departmenIds = new List<int>() { 10, 20, 30 };
var teachers = new List<int>() { 100, 200, 300 };
var students = new List<int>() { 1000, 2000, 3000 };
I am looking for a query that will return the data in a following fashion 我正在寻找一个查询,它将以以下方式返回数据
If all department ids exists in the json it will return entire data. 如果json中存在所有部门ID,它将返回整个数据。 If a department with a particular teacher is in the list then only return that teacher and the department. 如果列表中有一个具有特定老师的部门,则仅返回该老师和该部门。 like wise for the student. 对学生来说是明智的。
I tried this to test if it atleast work at the second level but I am getting all the teachers 我试图以此来测试它是否至少在第二级工作,但是我正在让所有老师
var list = allDeplrtments.Where(d => d.Teachers.Any(t => teachers.Contains(t.TeacherId))).ToList();
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
})
})
Would something like this work for you? 这样的事情对您有用吗?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.