我有包含學生分數的表的資料庫。每條記錄都包含 StudentName (nvarchar) 和 Score (int 從 1 到 5) 以及與記錄相關的其他資料 (日期、學科名稱等)
------------------------------------------------
StudentName Score Discipline Date
Bob 5 Asp.net 05/23/21
Bob 5 Html 05/23/21
Bob 5 C# 05/23/21
John 4 Asp.net 05/23/21
John 4 C# 05/23/21
Michael 3 Asp.net 05/23/21
Michael 3 Html 05/23/21
Michael 4 C# 05/23/21
我正在嘗試回傳結果視圖,在該視圖中,所有學生的姓名總和都將可見。
---------------------------
StudentName ScoreSum
Bob 15
John 8
Michael 10
我嘗試了以下解決方案,但 && 出現錯誤:
運算子'operator'不能應用于'type'和'type'型別的運算元代碼是Controller的一部分,公共ActionResult ViewStudentsBySumOfScore()是它的一種方法。
public ActionResult ViewStudentsBySumOfScore()
{
var db = new AllDbContext();
var ScoreSum = db.Scores
.Select(x =\> x.StudentName && x.Score)
.Sum();
return View();
}
如上所述,如何更改代碼以獲得結果?
uj5u.com熱心網友回復:
在為每個學生創建一個物件之前,您應該使用.GroupBy()對所有分數記錄進行分組,并使用為每個學生生成分數總和。StudentName.Sum()
如果您有一個用于存盤學生分數總和的課程,例如StudentScoreSum:
public class StudentScoreSum
{
public string StudentName { get; set; }
public int ScoreSum { get; set; }
}
,實作可以如下:
List<StudentScoreSum> scoreSum = db.Scores
.GroupBy(s => s.StudentName)
.Select(scoresByStudent => new StudentScoreSum {
StudentName = scoresByStudent.Key,
ScoreSum = scoresByStudent.Sum(s => s.Score)})
.ToList();
示例小提琴在這里。
回傳.GroupBy()值
假設資料庫表中條目的資料型別Scores實際上是Score,.GroupBy()操作回傳一個IEnumerable<Grouping<string, Score>>.
在.Select()操作中,scoresByStudent特此一Grouping<string, Score>;
string是組鍵的資料型別Score是組的物件集合中元素的資料型別
根據您的示例分數資料,.GroupBy()操作的結果將是三個分組。它們可以被可視化為:
| 鑰匙 | 物件集合 |
|---|---|
| “鮑勃” | { StudentName = "Bob", Score = 5 }{ StudentName = "Bob", Score = 5 }{ StudentName = "Bob", Score = 5 } |
| “約翰” | { StudentName = "John", Score = 4 }{ StudentName = "John", Score = 4 } |
| “邁克爾” | { StudentName = "Michael", Score = 3 }{ StudentName = "Michael", Score = 3 }{ StudentName = "Michael", Score = 4 } |
對于這三個組中的每一個,StudentScoreSum都會創建一個物件,使用組的鍵作為 ,并將組的物件集合中所有元素StudentName的值相加以生成.ScoreScoreSum
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/452688.html
標籤:asp.net-mvc 林克
上一篇:將值從視圖傳遞到控制器
