I have a problem that I have simplified and scratched his head. If I have a list of students, and I want to use LINQ to create a group of students by age, class, and the LastName, so I can cross them with a foreach nested loop, as if I did. Here is the 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) {
source share