2013-10-07 27 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();