Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/290.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/list/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 使用lambda从对象及其列表创建通用列表_C#_List_Lambda - Fatal编程技术网

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();