LINQ中的GroupBy问题
本文关键字:问题 GroupBy 中的 LINQ | 更新日期: 2023-09-27 18:30:04
首先抱歉问题标题不正确!
我有以下问题:
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
每行=相同标题的总和
我怎样才能达到这个结果?
谢谢!
您可以使用GroupBy
:
q.GroupBy(x => x.Title)
.Select(x => new
{
Title = x.Key,
Score = x.Sum(s => s.Score)
});