0

同じ 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);
}
4

3 に答える 3

5

SUBJECT定義でプロパティを宣言するTestScores場合、必要なものは次のとおりです。

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

結果はIEnumerable匿名型になり、各インスタンスにはSUBJECTメンバーSumが含まれます。

于 2013-10-07T15:47:24.530 に答える
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();
于 2013-10-07T16:08:09.790 に答える