列表<类>如何获取小计

本文关键字:获取 何获取 列表 | 更新日期: 2023-09-27 18:34:11

总结所有相同主题的测试分数并将总值放入每个实例的最简单方法是什么?

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);
}

列表<类>如何获取小计

假设您在TestScores定义中声明了 SUBJECT 属性,这就是您需要的:

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

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

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

这可能是你所追求的。

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();