2013-10-07 12 views
0

总结所有相同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); 
} 
+3

你可以使用'GroupBy'。 –

+0

具有相同主题的所有分数是否应具有相同的小计?或者应该是一个运行号码,即ID = 0将有小计10,ID = 1将有小计30? –

+0

您尚未分配任何值来键入您添加到'testScores'的任何'TestScore'对象。 –

回答

5

前提是你在TestScores定义声明SUBJECT属性,这是你所需要的:

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

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

2
testScores 
    .GroupBy(ts => ts.SUBJECT) 
    .Select(g => new { 
     Subject = g.Key, 
     Sum = g.Select(x => x.SCORE).Sum() 
     }) 
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();