【问题标题】:GroupBy Issue in LINQLINQ 中的 GroupBy 问题
【发布时间】:2014-11-12 11:46:46
【问题描述】:

首先抱歉问题标题不好!

我有以下查询:

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

每一行 = 相同标题的总和

我怎样才能达到这个结果?

谢谢!

【问题讨论】:

    标签: c# sql asp.net linq


    【解决方案1】:

    你可以使用GroupBy:

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

    【讨论】:

      猜你喜欢
      • 2011-06-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-10-23
      • 1970-01-01
      相关资源
      最近更新 更多