Home > Mobile >  Combine parent list & multiple child list using LINQ
Combine parent list & multiple child list using LINQ

Time:01-25

Trying to combine multiple child list collection and attaching to a single parent list, all the child's have a Id which is in common with parent Id.

List<Department> DepartmentList
List<Student> StudentList
List<Professor> ProfessorList

class ParentVM
{
    public List<Department> DepartmentList;
}

class Department
{
    public int Id { get; set; }
    Public List<Student> StudentList
    Public List<Professor> ProfessorList
}

class student
{
    public int Id { get; set; }
    Public int DepartmentId { get; set; }
    public int StudentName { get; set; }
}

class professor
{
    public int Id { get; set; }
    Public int DepartmentId { get; set; }
    public int ProfessorName { get; set; }
}

I have below query to attach a parent to a child:

 var departmentQuery =
    from dpt in DepartmentList
    join stu in StudentList on dpt.Id equals stu.DepartmentId
    group StudentList by DepartmentId;

foreach(var grp in departmentQuery) {
    grp.Key.StudentList = grp.ToList();
}

Using above query I will have to repeat above query again for ProfessorList & repeat foreach loop again to attach professor list to department collection, but how do I write query to attach all childrens to it's parents using one query and one foreach loop.

CodePudding user response:

I presume the Parent object has a List of Child objects and the Child object has a ParentId property that corresponds to the parents's Id.

class Parent
{
    public int Id { get; set; }
    public List<Child> Children { get; set; }
}

class Child
{
    public int Id { get; set; }
    public int ParentId { get; set; }
}

Assigning all the corresponding children from multiple lists can be done with the following:

parentList = parentList.Select(
    parent => new Parent 
    {
        Id = parent.Id, 
        Children = childList1.Union(childList2.Union(childList3))
            .Where(child => child.ParentId == parent.Id)
            .ToList()
    }
).ToList();

CodePudding user response:

Simple go through each Department object and assign its children lists:

foreach (var dept in DepartmentList) {
    dept.StudentList = StudentList.Where(s => s.DepartmentId == dept.Id).ToList();
    dept.ProfessorList = ProfessorList.Where(p => p.DepartmentId == dept.Id).ToList();
}
  •  Tags:  
  • Related