Linq查询摘要按列排序

时间:2013-04-17 18:57:49

标签: c# linq c#-4.0

场景就像这样

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  |

1 个答案:

答案 0 :(得分: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)
                              });