总结所有同一个SUBJECT的TestScore并将总值放到每个实例的最简单方法是什么?
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},
};
Run Code Online (Sandbox Code Playgroud)
有类似的东西吗?
foreach (TestScore ts in testScores)
{
ts.SUBTOTAL = Sum(testScores.SUBJECT == ts.SUBJECT);
}
Run Code Online (Sandbox Code Playgroud)
如果您SUBJECT在TestScores定义中声明了一个属性,那么这就是您所需要的:
var grouped = testScores.GroupBy(ts=>ts.SUBJECT)
.Select(g => new {SUBJECT = g.Key,
Sum = g.Sum(ts=> ts.SCORE)});
Run Code Online (Sandbox Code Playgroud)
结果将是一个IEnumerable匿名类型,其中每个实例都有SUBJECT和Sum成员.