简体   繁体   English

使用lambda从对象及其列表创建通用列表

[英]Create generic list from an object and its list using lambda

I am trying to create a "flat" generic list of objects from an object with a list of items in it. 我正在尝试从一个对象创建一个“平面”通用列表,其中包含一个项目列表。 Ill explain below: 我解释如下:

public class Student
{
   public string Name;
   public string Age;
}

public class Classroom
{
   public string Name;
   public List<Student> Students;
}

I now have a list of Classroom objects called List<Classroom> Classrooms each populated with a list of students, all i need is a generic list that will have the following information for each classroom and every student in all classrooms: 我现在有一个名为List<Classroom> Classrooms的Classroom对象List<Classroom> Classrooms每个对象都填充了一个学生列表,我需要的是一个通用列表,它将为每个教室和所有教室中的每个学生提供以下信息:

{Classroom.Name, Student.Name, Student.Age}

Thanks in advance. 提前致谢。

You could just use SelectMany Linq extension: 你可以使用SelectMany Linq扩展:

Classrooms.SelectMany(classroom => classroom.Students.Select(student => new 
{ 
    ClassroomName = classroom.Name, 
    StudentName = student.Name, 
    StudentAge = student.Age 
}))

You can get what you want like this: 你可以得到你想要的东西:

var results = (
    from room in Classrooms
    from student in room.Students
    select new { Room=room.Name, student.Name, student.Age }
).ToList();

This gets you a list of instances of an anonymous type. 这将为您提供匿名类型实例的列表。 It might be better to declare a class and use that instead - new MyClass(room.Name, etc) instead of new { Room=room.Name, etc } . 最好声明一个类并使用它 - new MyClass(room.Name, etc)而不是new { Room=room.Name, etc }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM