使用LINQ将对象和嵌套集合信息组合到一个新对象中

时间:2015-06-02 15:37:34

标签: vb.net linq

使用LINQ,是否可以将对象和该对象的嵌套集合中的属性组合到一个新对象中?因此,对于嵌套集合中的每个项目,我想创建一个新对象,其中嵌套对象信息与父对象的信息相结合。

使用示例场景,我尝试做类似的事情:

Teachers.Select(Function(item) New TeacherRecord() With
                                 {.TeacherId = item.Id, 
                                  .TeacherName = item.Name, 
                                  .StudentID = ? , 
                                  .StudentName = ?}).ToList()

示例类

Public Property Teachers as List(of Teacher) 

Public Class Teacher
    Public Property ID as Integer
    Public Property Name as String
    Public Property Room as String
    Public Property Students as List(of Student)
End class

Public Class Student
    Public Property ID as Integer
    Public Property Name as String
End Class

Public Class TeacherRecord
    Public Property TeacherId as Integer
    Public Property TeacherName as String
    Public Property StudentId as Integer
    Public Property StudentName as String
End Class

2 个答案:

答案 0 :(得分:1)

你需要使用SelectMany,我对VB不太了解,但这就是你在C#中的表现:

List<TeacherRecord> records = teachers.SelectMany(t => t.Students, (t, s) =>
                              new TeacherRecord { TeacherId = t.ID, 
                                  TeacherName = t.Name, 
                                  StudentId = s.ID, 
                                  StudentName = s.Name }).ToList();

答案 1 :(得分:0)

您需要重新考虑您与教师或学生之间的TeacherRecord关系 - 现在还不清楚,但通常您可以将ViewData与代码组合在一起,代码将如下所示:

void Main(){
List<Teacher> teacher = new List<Teacher>();
List<Student> student = new List<Student>();
student.Add(new Student{ID=1,Name="Tom"});
student.Add(new Student{ID=2,Name="Jerry"});

teacher.Add(new Teacher{ID=1
                    ,Name="John"
                    ,Room = "Room A"
                    ,Students = student});



var combined = (from t in teacher
        select t).ToList();


    }

// Define other methods and classes here
public class Teacher
{
public int ID { get; set; }
public string Name { get; set; }
public string Room { get; set; }
public List<Student> Students { get; set; }
}

public class Student
{
public int ID { get; set; }
public string Name { get; set; }
}

public class TeacherRecord
{
public int TeacherId { get; set; }
public string TeacherName { get; set; }
public int StudentId { get; set; }
public string StudentName { get; set; }
}

结果将是这样的:

enter image description here