【问题标题】:How to group by using enums in LINQ c# and find max value如何在 LINQ c# 中使用枚举进行分组并找到最大值
【发布时间】:2021-05-20 17:34:43
【问题描述】:
public enum Department{ Accounts, Technology, Architecture, MBA };
public class Student
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public int ID { get; set; }
    public int ExamScores;
    public Department dep;
}

我有一份学生名单。我应该如何显示使用 LINQ 从每个部门获得最高分的学生。 我试过了,但没成功,请指教。

【问题讨论】:

  • 请向我们展示您的尝试。此外,这将有助于查看输入和所需的输出。最后 - 是您感兴趣的 EF 查询(或其他一些 ORM)还是“普通”LINQ-to-objects。
  • 学生 .GroupBy(s => s.dep).Select(g => ( g.Key, g.Select(v => v.ExamScores).Max() ) );跨度>

标签: c# .net linq lambda


【解决方案1】:

正如评论的那样,始终包含您尝试过的内容是个好主意。两者都是因为它表明你已经做出了努力,并且有人可能会帮助指出你哪里出错了,你会从中学到更多。

话虽如此,您可以通过分两步分组来解决这个问题:

  1. dep分组
  2. 然后由ExamScores

最后对结果进行排序以获得得分最高的结果:

// "one"-liner:
var results = students.GroupBy(s => s.dep)
    .Select(depGroup => depGroup.GroupBy(s => s.ExamScores)
        .OrderByDescending(scoreGroup => scoreGroup.Key) // Key is the ExamScores
        .First()); // First = Get the first group, which has the highest score

有关示例,请参阅 this fiddle

// Example output:
// ID  dep           ExamScores
// 3   Accounts      9
// 7   Accounts      9
// 4   Technology    8
// 6   Architecture  6

【讨论】:

    【解决方案2】:

    您可以按部门对学生进行分组,然后查找每个组中所有分数与该部门的最高分数相匹配的学生:

    var departmentStudents = students.GroupBy(s => s.dep);
    
    foreach (var department in departmentStudents)
    {
        var highScore = department.Max(ds => ds.ExamScores);
    
        var bestStudents = department
            .Where(student => student.ExamScores == highScore)
            .Select(student => $"{student.FirstName} {student.LastName}");
    
        Console.WriteLine($"Sudents with best score in the {department.Key} Dept.:");
        Console.WriteLine($" - {string.Join("\r\n - ", bestStudents)}");
    }
    

    【讨论】:

      【解决方案3】:

      假设您有以下学生列表:

      List<Student> students = new List<Student> {
                      new Student("x", "y", 1, 10, Department.Accounts),
                      new Student("p", "q", 2,20, Department.Accounts),
                      new Student("p2", "q2", 2, 20, Department.Accounts),
                      new Student("a", "b", 3, 30, Department.Technology),
                      new Student("m", "n", 4, 40, Department.Technology),
                      new Student("m2", "n2", 4, 40, Department.Technology),
                  };
      

      现在您可以按部门分组并通过以下方法找到最高分的学生:

      var groupsByDept = students.GroupBy(a => (a.dep.ToString()));
      List<Student> studentsByHighestMarksAndDeptList = groupsByDept.SelectMany(a => a.Where(b => b.ExamScores == a.Max(c => c.ExamScores))).ToList();
      

      这将给出以下结果:

      【讨论】:

        猜你喜欢
        • 2011-01-03
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2010-12-17
        • 2016-04-03
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多