簡體   English   中英

如何使用 LINQ c# 中的枚舉進行分組並找到最大值

[英]How to group by using enums in LINQ c# and find max value

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 顯示從每個部門獲得最高分的學生。 我已經嘗試過但無法成功。請建議。

正如所評論的,始終包含您嘗試過的內容是一個好主意。 兩者都是因為它表明您已經做出了努力,並且有人可能會幫助指出您出錯的地方,您將從中學到更多。

話雖如此,您可以通過分兩步分組來解決此問題:

  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

有關示例,請參見此小提琴

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

您可以按部門對學生進行分組,然后查找每個組中得分與該部門最高分數匹配的所有學生:

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)}");
}

假設您有以下學生列表:

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

這將給出以下結果: 在此處輸入圖像描述

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM