Aaron Reese Aaron Reese - 1 month ago 11
C# Question

what is the best way to get an ordered list from a complex object where the list elements are from a second generation child collection

I am new to MVC and I am trying to display an ordered list of a second generation collection. Rather then confuse the issue with my particular data set; please can you advise how you would do the following from the ConsotoUniversity example.
Instructors have a collection of courses.
Course has a collection of Students

How would I list all of the Students by Surname for each teacher. Assuming the viewModel has Instructor.Courses.Students I know that in the view I can do

@foreach (var instructor in @Model.Instructors)
{
<h2>@instructor.FullName</h2>

foreach(var course in instructor.Courses)
{
foreach(var student in course.Students.OrderBy(s=>s.LastName))
{
<p>@student.LastName, @student.FirstName</p>
}
}
}


but this will only print the names in order by course so if I had two courses: Coding and Maths with the students: Coding = John Jones & Tim Green, Maths = Adam Smith & Aaron Aardvark I would get a list that looks like:


  • Green,Tim

  • Jones, John

  • Aardvark, Aaron

  • Smith, Adam



but what I want is:


  • Aardvark, Aaron

  • Green,Tim

  • Jones, John

  • Smith, Adam



In my particular use case there would not be duplicates of students.

Answer

You can use SelectMany() to aggregate the child lists into a single list, then sort that. Something like this:

foreach (var student in instructor.Courses.SelectMany(c => c.Students).OrderBy(s => s.LastName))
{
    <p>@student.LastName, @student.FirstName</p>
}
Comments