如何在C# Linq中为分组项添加编号 给同School同Age学生分配GroupID
解决方案
你原来的代码只筛选出了符合分组条件的学生,丢失了其余学生,且没有做GroupID的映射分配,可通过先构造分组ID映射字典,再遍历原列表赋值的方式实现需求:
完整实现代码
List<Student> studentList = new List<Student>() { new Student() { StudentID = 1, StudentName = "John", Age = 18, School = "ABC" , GroupID = 0} , new Student() { StudentID = 2, StudentName = "Steve", Age = 21, School = "DEF", GroupID = 0 } , new Student() { StudentID = 3, StudentName = "Bill", Age = 21, School = "DEF", GroupID = 0 } , new Student() { StudentID = 4, StudentName = "Josh" , Age = 20, School = "DEF", GroupID = 0 }, new Student() { StudentID = 5, StudentName = "Jack" , Age = 19, School = "JKL", GroupID = 0 }, new Student() { StudentID = 6, StudentName = "Thomas" , Age = 18, School = "MNO", GroupID = 0 }, new Student() { StudentID = 7, StudentName = "Rich" , Age = 22, School = "PQR", GroupID = 0 }, new Student() { StudentID = 8, StudentName = "Robert" , Age = 22, School = "PQR", GroupID = 0 }, new Student() { StudentID = 9, StudentName = "John" , Age = 20, School = "PQR", GroupID = 0 }, new Student() { StudentID = 10, StudentName = "Emma" , Age = 20, School = "XYZ", GroupID = 0 }}; // 第一步:为满足人数≥2的「Age+School」分组分配自增ID,存入字典 var groupIdDict = studentList .GroupBy(s => new { s.Age, s.School }) .Where(g => g.Count() >= 2) .Select((group, index) => new { GroupKey = group.Key, GroupId = index + 1 }) .ToDictionary(item => item.GroupKey, item => item.GroupId); // 第二步:遍历原列表生成输出,保留所有学生,仅为符合条件的分组赋值GroupID List<Student> outputList = studentList.Select(s => { s.GroupID = groupIdDict.TryGetValue(new { s.Age, s.School }, out int id) ? id : 0; return s; }).ToList();
不修改原对象的写法
如果需要保留原始studentList里的对象属性不变,可以改成如下写法,生成全新的Student列表:
List<Student> outputList = studentList.Select(s => new Student { StudentID = s.StudentID, StudentName = s.StudentName, Age = s.Age, School = s.School, GroupID = groupIdDict.TryGetValue(new { s.Age, s.School }, out int id) ? id : 0 }).ToList();
运行后输出结果完全符合要求:
- Steve、Bill的GroupID为1
- Rich、Robert的GroupID为2
- 其余学生GroupID保持0
内容的提问来源于stack exchange,提问作者user17011975
相关产品推荐
相关产品推荐

