[英]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. 我是MVC的新手,我正在尝试显示第二代集合的有序列表。 Rather then confuse the issue with my particular data set; 而不是将问题与我的特定数据集混淆; please can you advise how you would do the following from the ConsotoUniversity example. 请告诉你如何从ConsotoUniversity的例子中做到以下几点。 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 假设viewModel有Instructor.Courses.Students,我知道在视图中我可以做到
@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: 但这只会按顺序打印名称,所以如果我有两门课程:与学生一起编码和数学:Coding = John Jones和Tim Green,Maths = Adam Smith和Aaron Aardvark我会得到一个如下列表:
but what I want is: 但我想要的是:
In my particular use case there would not be duplicates of students. 在我的特定用例中,不会有重复的学生。
You can use SelectMany()
to aggregate the child lists into a single list, then sort that. 您可以使用SelectMany()
将子列表聚合到单个列表中,然后对其进行排序。 Something like this: 像这样的东西:
foreach (var student in instructor.Courses.SelectMany(c => c.Students).OrderBy(s => s.LastName))
{
<p>@student.LastName, @student.FirstName</p>
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.