列出<class>如何获得小计</class>

时间:2013-10-07 15:40:47

标签: 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},    
};

有类似的东西吗?

foreach (TestScore ts in testScores)
{
    ts.SUBTOTAL = Sum(testScores.SUBJECT == ts.SUBJECT);
}

3 个答案:

答案 0 :(得分:5)

如果您在SUBJECT定义中声明了TestScores属性,那么这就是您所需要的:

var grouped = testScores.GroupBy(ts=>ts.SUBJECT)
                        .Select(g => new {SUBJECT = g.Key, 
                                          Sum = g.Sum(ts=> ts.SCORE)});

结果将是匿名类型的IEnumerable,其中每个实例都有SUBJECTSum个成员。

答案 1 :(得分:2)

testScores
    .GroupBy(ts => ts.SUBJECT)
    .Select(g => new {
        Subject = g.Key, 
        Sum = g.Select(x => x.SCORE).Sum()
        })

答案 2 :(得分:1)

我认为这可能就是你所追求的。

public class TestScore
{
    public int ID { get; set; }
    public int TYPE { get; set; }
    public int SCORE { get; set; }
    public string SUBJECT { 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},    
};

var tsList = from ts in testScores 
             group new {ts.SUBJECT,ts.SCORE} by ts.SUBJECT into grp 
             select new { Subject = grp.Key, Subtotal = grp.Sum(x => x.SCORE) };

foreach(var t in tsList)
    Console.WriteLine("Subject: {0} - Subtotal: {1}", t.Subject, t.Subtotal);

Console.WriteLine("Press Any Key to Exit...");    
Console.ReadKey();