首页 > 解决方案 > 使用 Linq 进行分组/排序

问题描述

我有这个学生成绩列表:

年级 学生
10 约翰
10 玛丽
9 彼得
9 艾莉森

我想像这样对它们进行分组:

年级 学生们
10 约翰,玛丽
9 彼得,艾莉森

所以我得到了这个 Linq 命令:

var gradesAndStudents = studentsGrades.GroupBy(p => p.grade, p => p.student,
    (key, g) => new { Grade = key, Students = g.ToList() });

所以现在结果被分组和排序,成绩显示所有学生的成绩:

年级 学生们
10 10、约翰
10、玛丽
9 9、彼得
9、艾莉森

但是我怎样才能让学生的名字只作为一个字符串呢?

标签: c#linq

解决方案


试试这个

var gradesAndStudents = from p in studentsGrades
              group p.student by p.grade into g
              select new { Grade= g.Key, Students =string.Join(", ", g.ToList()) };

推荐阅读