假設我有一個定義簡單的學生類:
public string Name { get; set; }
public int[] Marks { get; set; }
現在我創建一個學生串列:
List<Student> students = new List<User>();
students.Add(new Student("John", { 3, 4, 5, 5, 4 }));
students.Add(new Student("Adam", { 2, 5, 5, 1, 3 }));
students.Add(new Student("Katy", { 6, 3, 2, 2, 3 }));
現在,我需要創建一個 LINQ 查詢,它將檢索所有學生中最好的單個分數。在這種情況下,它將是 6,因為這是所有陣列中的最大值。我想出了這樣的事情:
var query =
from student in students
where student.Marks is not null
group student by student.Marks into studentMarks
group studentMarks.Key.Max() by studentMarks.Key.Max() into studentMarks
orderby studentMarks.Key descending
select studentMarks.Key;
Console.WriteLine(query.ElementAt(0)); // output: 6
現在,我怎樣才能以更好的方式撰寫它,以便它只輸出單個 int,所以我可以簡單地說:
Console.WriteLine(query);
uj5u.com熱心網友回復:
使用SelectMany:
int topMark = students.SelectMany(s => s.Marks).Max() // 6
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/482047.html
