How to sort within a group after grouping in LINQ?
In LINQ, you can use the OrderBy or OrderByDescending methods to sort the results after grouping.
You can write a LINQ query to group a list of students by class and sort them by name within each class.
var students = new List<Student>();
// 分组并在组内排序
var groupedStudents = students
.GroupBy(s => s.Class)
.Select(g => new
{
Class = g.Key,
Students = g.OrderBy(s => s.Name) // 在组内按姓名排序
});
// 遍历结果
foreach(var group in groupedStudents)
{
Console.WriteLine("班级:" + group.Class);
foreach(var student in group.Students)
{
Console.WriteLine("姓名:" + student.Name);
}
}
In this example, the GroupBy method groups the list of students by class, then sorts the students within each class by name using the OrderBy method. Finally, we use the Select method to create a new result object that includes the class and the sorted list of students. When iterating through the results, we can see that the students within each class are sorted by name.