3

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.

2 Answers 2

3

You could just use SelectMany Linq extension:

Classrooms.SelectMany(classroom => classroom.Students.Select(student => new 
{ 
    ClassroomName = classroom.Name, 
    StudentName = student.Name, 
    StudentAge = student.Age 
}))
Sign up to request clarification or add additional context in comments.

1 Comment

Perfect, it was the selectMany that i was missing, @Blogrbeard im sure yours will also work, i was looking for a lambda answer, but thanks too!
2

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 }.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.