Liststudents = new List (); // ...Students added to list... var groupedStudents = students.GroupBy(s => s.GradeLevel); foreach (var group in groupedStudents) { Console.WriteLine("Students in grade level " + group.Key + ":"); foreach (var student in group) { Console.WriteLine(student.Name); } }
ListThis code creates a dictionary where the keys are the categories and the values are lists of products. The products are then looped through and added to their respective category lists. Finally, the groups are iterated through to print out the products in each category. The packages used in these examples are LINQ and System.Collections.Generic, which are both part of the .NET Framework.products = new List (); // ...Products added to list... Dictionary > groupedProducts = new Dictionary >(); foreach (var product in products) { if (groupedProducts.ContainsKey(product.Category)) { groupedProducts[product.Category].Add(product); } else { groupedProducts[product.Category] = new List () { product }; } } foreach (var group in groupedProducts) { Console.WriteLine("Products in category " + group.Key + ":"); foreach (var product in group.Value) { Console.WriteLine(product.Name); } }