列出<class>如何获得小计

See*_*Lee 0 c# linq list

总结所有同一个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)

Adr*_*iro 5

如果您SUBJECTTestScores定义中声明了一个属性,那么这就是您所需要的:

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匿名类型,其中每个实例都有SUBJECTSum成员.