Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create generic list from an object and its list using lambda

Tags:

c#

list

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:

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

Thanks in advance.

like image 632
user3322417 Avatar asked May 27 '26 09:05

user3322417


1 Answers

You could just use SelectMany Linq extension:

Classrooms.SelectMany(classroom => classroom.Students.Select(student => new 
{ 
    ClassroomName = classroom.Name, 
    StudentName = student.Name, 
    StudentAge = student.Age 
}))
like image 84
awesoon Avatar answered May 30 '26 05:05

awesoon



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!