2013-04-17 108 views
3

的情況是這樣的Linq查詢彙總柱與排序

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 ANS val_2爲每名

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

回答

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) 
    }; 

O r如果您更喜歡流利的語法:

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) 
           });