c# - 使用 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、艾莉森 |
但是我怎样才能让学生的名字只作为一个字符串呢?
解决方案
试试这个
var gradesAndStudents = from p in studentsGrades
group p.student by p.grade into g
select new { Grade= g.Key, Students =string.Join(", ", g.ToList()) };
推荐阅读
- r - 类似交叉连接的操作(有例外)
- javascript - 扩展 OnClick 单个 div 并重新排列其余部分
- android - 如何以编程方式链接联系电话?
- java - Android Studio & Firebase 数据库问题
- python - 如何计算损失梯度以对 Keras 模型中的输入进行建模?
- sql-server-2012 - 根据条件更新随机行
- compiler-flags - CMake:禁止开发人员警告
- reactjs - 如何使用 react-create 命令创建扩展名为 .tsx 的反应组件
- ios - 快速为不同的现有类实现相同的属性
- javascript - 将 Json 中的特定属性刮到新的 Json 中