總結所有相同SUBJECT的TestScore並將總值放到每個實例的最簡單方法是什麼?列表<class>如何獲得小計
public class TestScore
{
public int ID { get; set; }
public int SUBJECT { get; set; }
public int SCORE { get; set; }
public int SUBTOTAL { get; set; }
}
List<TestScore> testScores = new List<TestScore>{
new TestScore{ ID = 0, SUBJECT = "MATH", SCORE = 10},
new TestScore{ ID = 1, SUBJECT = "MATH", SCORE = 20},
new TestScore{ ID = 2, SUBJECT = "ENGLISH", SCORE = 10},
new TestScore{ ID = 3, SUBJECT = "ENGLISH", SCORE = 20},
new TestScore{ ID = 4, SUBJECT = "ENGLISH", SCORE = 30},
};
是否有類似的東西?
foreach (TestScore ts in testScores)
{
ts.SUBTOTAL = Sum(testScores.SUBJECT == ts.SUBJECT);
}
你可以使用'GroupBy'。 –
具有相同主題的所有分數是否應具有相同的小計?或者應該是一個運行號碼,即ID = 0將有小計10,ID = 1將有小計30? –
您尚未分配任何值來鍵入您添加到'testScores'的任何'TestScore'對象。 –