c# - 为 Linq 中的分组项目添加编号
问题描述
我需要添加GroupID
到有重复School
和重复的学生Age
(史蒂夫、比尔、里奇、罗伯特)。输出需要以原始列表格式 ( List<Student>
) 进行转换。
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 }};
List<Student> outputList = studentList
.GroupBy(s => new { s.Age, s.School })
.Where(g => g.Count() >= 2)
.SelectMany(g => g)
.ToList();
输出:
史蒂夫和比尔:
GroupID = 1
里奇和罗伯特:
GroupID = 2
任何帮助表示赞赏。
解决方案
SelectMany
有一个重载传入项目的索引,所以你可以这样做:
List<Student> outputList = studentList
.GroupBy(s => new { s.Age, s.School })
.Where(g => g.Count() >= 2)
.SelectMany((g, i) => g.Select(s =>
{
s.GroupID = i;
return s;
}))
.ToList();
这确实感觉有点 hacky(我不喜欢在 Linq 中改变对象)所以我可能会做这样的事情:
List<Student> outputList = studentList
.GroupBy(s => new { s.Age, s.School })
.Where(g => g.Count() >= 2)
.SelectMany((g, i) => g.Select(s => new Student
{
StudentID = s.StudentID,
StudentName = s.StudentName,
Age = s.Age,
School = s.School,
GroupID = i
}))
.ToList();
推荐阅读
- webpack-dev-server - webpack-dev-server 在 publicPath: '/' 时使用“webpack-dev-server”作为路径
- python - Python“TypeError:'int'和'NoneType'的实例之间不支持'<'”
- python - 加载 URL 模式而不激活它们?
- reactjs - 将 create-react-app 代理设置从 1.x 更新到 2.x
- javascript - 使用填充字符串的自定义类型扩展 Joi
- angular - 在 Angular 中实现外部 Cludo 脚本的最佳实践
- html - 在 HTML5 页面中显示德语重音字符的问题
- android - Android Studio - 移除的依赖不会从外部库中移除
- ffmpeg - 作为服务运行时,ffmpeg -hls_time 选项无法正常工作
- android - 我可以在一个 HTTP 请求中从谷歌距离矩阵 api 获取所有数据吗?