c# - List<class> how to get subtotal -


what simplest way sum testscore same subject , put total value each instance?

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

is there like?

foreach (testscore ts in testscores) {     ts.subtotal = sum(testscores.subject == ts.subject); } 

provided declare subject property in testscores definition, need:

var grouped = testscores.groupby(ts=>ts.subject)                         .select(g => new {subject = g.key,                                            sum = g.sum(ts=> ts.score)}); 

the result ienumerable of anonymous type, each instance have subject , sum members.


Comments

Popular posts from this blog

c++ - CryptStringToBinary API behavior -

java.util.scanner - How to read and add only numbers to array from a text file -

iphone - Three second countdown in cocos2d -