c# - 为 Linq 中的分组项目添加编号

标签 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 有一个 overload传递项目的索引,这样你就可以这样做:

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();

这确实有点老套(我不喜欢在 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();

关于c# - 为 Linq 中的分组项目添加编号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69345565/

相关文章:

c# - 如何通过 C# 中的反射提取泛型方法约束?

c# - 并行运行多个任务

c# - 从 mkv/media 读取字幕

c# - Entity Framework 中的 System.Data.ProviderIncompatibleException

c# - 枚举本身不是 IEnumerable 的集合?

linq - Entity Framework 代码中的多对多映射优先

c# - 图表工具在 Visual Studio 中显示为灰色

sql - LINQ 在查询中插入 'ESCAPE N' ~'

c++ - C++ 中的 C# Linq 表达式

c# - 将 Queryable<T> 翻译回 IMongoQuery