如何使用LINQ按姓氏首字母对学生进行分组?
问题分析与解决
你的代码存在两个核心问题,导致没有输出且未完成「按姓氏首字母分组」的需求:
- 仅提取了学生姓氏的首字母,未实现分组逻辑
- 完全没有添加输出代码,终端自然不会显示内容
修正后的代码
using System; using System.Linq; using System.Collections.Generic; public class Program { public static void Main() { // Student collection List<Student> studentList = new List<Student>() { new Student {First="Bob", Last="Jones", ID=111, Age=15, Scores= 5}, new Student {First="Bob", Last="Jones", ID=111, Age=15, Scores= 10}, new Student {First="Claire", Last="Simpson", ID=112, Age=17, Scores= 5}, new Student {First="John", Last="Feetham", ID=113, Age=21, Scores= 10}, new Student {First="Jonathan", Last="Potts", ID=114, Age=10, Scores= 10}, new Student {First="Pepe", Last="Garcia", ID=115, Age=20, Scores= 5}, new Student {First="Samantha", Last="Fakhouri", ID=116, Age=17, Scores= 5}, new Student {First="Roger", Last="Song", ID=117, Age=19, Scores= 5}, new Student {First="Hugo", Last="Garcia", ID=118, Age=15, Scores= 10}, new Student {First="Richard", Last="Ammerman", ID=119, Age=14, Scores= 10}, new Student {First="Kevin", Last="Adamson", ID=120, Age=11, Scores= 10}, new Student {First="Jeet", Last="Singh", ID=121, Age=12, Scores= 10} }; // 按姓氏首字母分组 var groupedStudents = studentList.GroupBy(s => s.Last.First()); // 遍历分组并输出结果 foreach (var group in groupedStudents) { Console.WriteLine($"姓氏首字母: {group.Key}"); foreach (var student in group) { Console.WriteLine($" 学生: {student.First} {student.Last}, ID: {student.ID}, 年龄: {student.Age}"); } Console.WriteLine(); // 分隔不同分组 } } } public class Student{ public string First { get; set; } public string Last { get; set; } public int Age { get; set; } public int ID { get; set; } public int Scores { get; set;} }
关键修改说明
- 用
GroupBy(s => s.Last.First())替代原代码的Select,实现按姓氏首字母分组:得到的groupedStudents是分组集合,每个分组的Key为姓氏首字母,分组内包含对应首字母的所有学生。 - 添加两层
foreach循环遍历分组结果,并用Console.WriteLine输出每个分组的详细信息,让终端能显示分组内容。
内容的提问来源于stack exchange,提问作者Cutty
相关产品推荐
相关产品推荐

