我有一個這樣的清單:
List<Student> students = new List<Student>
{
new Student { Name = "M", Scores = new int[] { 94, 92, 91, 91 } },
new Student { Name = "I", Scores = new int[] { 66, 87, 65, 93, 86} },
new Student { Name = "C", Scores = new int[] { 76, 61, 73, 66, 54} },
new Student { Name = "D", Scores = new int[] { 94, 55, 82, 62, 52} },
new Student { Name = "P", Scores = new int[] { 91, 79, 58, 63, 55} },
new Student { Name = "E", Scores = new int[] { 74, 85, 73, 75, 86} },
new Student { Name = "P", Scores = new int[] { 73, 64, 53, 72, 68} },
}
有沒有什么辦法可以計算每個學生的平均成績,并按范圍顯示。結果將是這樣的:
Score > 90 and < 100
M(student name) 92 (average score)
Score > 80 and < 90
P 86.8
I 83.4
Y 82.4
我還需要計算多少個范圍。例如,對于上面的結果,我們有兩個范圍:(>90 and <100) 和 (>80 and <90)。
我已經知道如何計算平均分數,但是我堅持將它們分組到范圍內并僅使用 LINQ 計算范圍的數量。
我想學習怎么做。
uj5u.com熱心網友回復:
首先,請注意,您將需要一個平均分數恰好為 90 的情況。我將假設這將由較高的存盤桶處理,但如果您需要較低的存盤桶,則可以更改邏輯。
最好根據分數的“等級字母”計算和分組,因為它是一個字母,并且字母可以很容易地按字母順序排列。
var studentsByGrade = students
.Select(x => new {
x.Name,
AvgScore = x.Scores.Average()
})
.GroupBy(x => GetGradeLetter(x.AvgScore));
這將使用輔助方法。
private static string GetGradeLetter(double score)
{
if (score is >= 90)
return "A";
if (score is >= 80)
return "B";
// add more as you'd like
return "ZZZ";
}
值得一提的是,你并不需要在這里顯示字母-它只是使用,因為它的方便做排序,并且最有可能的就是你到底是什么了使用反正。通常,您會將低于“60”的任何內容標記為一組,因為(至少在美國學校系統中)這意味著“F”。
要顯示結果,請使用兩個 foreach。
foreach (var grade in studentsByGrade.OrderBy(x => x.Key))
{
foreach (var student in grade.OrderByDescending(x => x.AvgScore))
{
Console.WriteLine($"{student.Name} {student.AvgScore}");
}
Console.WriteLine();
}
uj5u.com熱心網友回復:
您可以使用 LINQ 的Average,Select和的組合GroupBy以及一些算術:
var result = string.Join("\r\n",
students.Select(s =>
(s.Name, Average: s.Scores.Average(sc => (double)sc)))
.GroupBy(s => (int)Math.Ceiling(s.Average / 10))
.OrderByDescending(g => g.Key)
.Select(g =>
$"Score >= {g.Key * 10 - 10} and < {g.Key * 10}\r\n"
string.Join("\r\n", g.Select(s => $" {s.Name} {s.Average:F1}"))
);
或略有不同
var result = string.Join("\r\n",
students.Select(s =>
(s.Name, Average: s.Scores.Average(sc => (double)sc)))
.GroupBy(s => (int)Math.Ceiling(s.Average / 10))
.OrderByDescending(g => g.Key)
.SelectMany(g =>
g.Select(s => $" {s.Name} {s.Average:F1}")
.Prepend($"Score >= {g.Key * 10 - 10} and < {g.Key * 10}\r\n"))
);
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/318216.html
