3

场景是这样的

public class Test {
   public string name;
   public int val1;
    public int val1;
}

name |val 1 |val 2|
'aa' | 10   | 4   | 
'aa' | 30   | 5   | 
'bb' | 14   | 4   |
'bb' | 16   | 6   | 
'cc' | 5    | 5   |
'cc' | 2    | 1   |
'cc' | 1    | 1   |

按名称分组并为每个名称获取摘要 val_1 和 val_2 的最佳方法是什么

作为

name |val 1 |val 2|
'aa' | 40   | 9   | 
'bb' | 30   | 10  | 
'cc' | 8    |  7  |
4

1 回答 1

7

尝试这个

var results =
    from t in db.Tests
    group t by t.name into g
    orderby g.Key
    select new
    {
        name = g.Key,
        val_1 = g.Sum(x => x.val_1),
        val_2 = g.Sum(x => x.val_2)
    };

或者,如果您更喜欢流畅的语法:

var results = db.Tests.GroupBy(t => t.name)
                      .OrderBy(g => g.Key)
                      .Select(g => new
                              {
                                  name = g.Key,
                                  val_1 = g.Sum(x => x.val_1),
                                  val_2 = g.Sum(x => x.val_2)
                              });
于 2013-04-17T18:59:46.393 回答