C# 使用lambda从对象及其列表创建通用列表
我试图从一个包含项目列表的对象创建一个“平面”通用对象列表。我将解释如下:C# 使用lambda从对象及其列表创建通用列表,c#,list,lambda,C#,List,Lambda,我试图从一个包含项目列表的对象创建一个“平面”通用对象列表。我将解释如下: public class Student { public string Name; public string Age; } public class Classroom { public string Name; public List<Student> Students; } 提前感谢。您可以使用Linq扩展: Classrooms.SelectMany(classroom
public class Student
{
public string Name;
public string Age;
}
public class Classroom
{
public string Name;
public List<Student> Students;
}
提前感谢。您可以使用Linq扩展:
Classrooms.SelectMany(classroom => classroom.Students.Select(student => new
{
ClassroomName = classroom.Name,
StudentName = student.Name,
StudentAge = student.Age
}))
你可以像这样得到你想要的:
var results = (
from room in Classrooms
from student in room.Students
select new { Room=room.Name, student.Name, student.Age }
).ToList();
这将获得匿名类型的实例列表。最好是声明一个类并使用它-
newmyclass(room.Name等)
而不是new{room=room.Name等}
完美,我缺少的是selectMany,@Blogrbeard我相信你的也可以,我正在寻找lambda的答案,但也谢谢!
var results = (
from room in Classrooms
from student in room.Students
select new { Room=room.Name, student.Name, student.Age }
).ToList();