I have a problem which I’ve simplified down and have been scratching my head at. If I have a list of students and I want to use LINQ to produce a group of students by Age, Grade, and LastName so I can traverse them with a nested foreach loop how would I go about this. Here is some code:
class Student
{
public int Grade;
public int Age;
public string LastName;
}
public void SomeMethod()
{
Student student1 = new Student() { Age = 10, Grade = 100, LastName = "Smith"};
Student student2 = new Student() { Age = 10, Grade = 90, LastName = "Jones" };
Student student3 = new Student() { Age = 10, Grade = 50, LastName = "Bob" };
Student student4 = new Student() { Age = 10, Grade = 100, LastName = "Smith" };
Student student5 = new Student() { Age = 11, Grade = 10, LastName = "Bob" };
Student student6 = new Student() { Age = 11, Grade = 30, LastName = "Jones" };
Student student7 = new Student() { Age = 13, Grade = 90, LastName = "Bob" };
Student student8 = new Student() { Age = 13, Grade = 90, LastName = "Smithy" };
Student student9 = new Student() { Age = 15, Grade = 100, LastName = "Smith" };
Student student10 = new Student() { Age = 15, Grade = 0, LastName = "Smith" };
List<Student> studentList = new List<Student>()
{
student1,student2,student3,student4,student5,student6,student7,student8,student9,student10
};
var studentGroups = from student in studentList
group student by student.Age into studentAgeGroup
from studentAgeGradeGroup in
(
from student in studentAgeGroup
group student by student.Grade
)
group studentAgeGradeGroup by studentAgeGroup.Key;
foreach (var ageGroup in studentGroups)
{
foreach (var gradeGroup in ageGroup)
{
foreach (var innerGroupElement in gradeGroup)
{
// At this point they are grouped by age and grade but I would also like them to be grouped by LastName
}
}
}
}
How about?
and looping through each element in studentGroups, you can access
Agebysg.Key.Ageand so on.