LINQ中的GroupBy问题

时间:2014-11-12 11:46:46

标签: c# sql asp.net linq

首先抱歉错误的问题标题!

我有以下查询:

var q = 
        from t1 in UserScores.Where(c=>c.UserID == 1)
        from t2 in Points.Where(c => c.ID == t1.ID)
        from t3 in CouponsPackages.Where(c => c.ID == t1.ID).DefaultIfEmpty()

        group t2 by new
        {
            t1.ID,
            t1.Value,           
            t1.Operand,
            t2.Title,
            t2.Rate,
            t3.ScoreAmount
        } into g 

        select new {        
            g.Key.Title,
            Score = (g.Key.ID < 3
                ? (g.Key.ID == 1 ? g.Key.Value : g.Key.ScoreAmount)
                : (g.Key.Operand == 1 ? g.Key.Rate * 1 : g.Key.Rate * -1))
        };

结果如下:

Title     Score
A         10
A         50
B         30
C         60
C         -30 

但我需要这个:

Title     Score
A         60
B         30
C         30

每一行=相同标题的总和

我如何达到这个结果?

谢谢!

1 个答案:

答案 0 :(得分:0)

您可以使用GroupBy

q.GroupBy(x => x.Title)
.Select(x => new 
{ 
     Title = x.Key, 
     Score = x.Sum(s => s.Score) 
});