2013-06-25 189 views
12

來總結我有一個數據表是這樣的:Linq查詢通過

Category   Description  CurrentHours  CTDHours 
LC1    Cat One     5    0 
LC2    Cat Two     6    0 
LC3    Cat Three    18    0 
LC1    Cat One     0    9 
LC2    Cat Two     0    15 
LC4    Cat Four    0    21 

,我需要集團和點心這樣:

Category   Description  CurrentHours  CTDHours 
LC1    Cat One     5    14 
LC2    Cat Two     6    21 
LC3    Cat Three    18    0 
LC4    Cat Four    0    21 

換句話說,我需要總結兩按類別和說明列分組的小時列。

我知道我可以建立一個新表並循環訪問現有數據並將數據彙總到新表中,但我認爲使用Linq會有更簡單的方法。我搜索了幾個小時,但是我發現的所有例子似乎都不符合我想要做的。

順便說一句,創建數據表的odbc驅動程序不具備子查詢等功能,或者我只是使用SQL完成它。

感謝,

約翰

回答

30

使用匿名對象組按類別和說明。這是LINQ到數據集查詢返回分組小時:如果您在查詢數據庫(而不是從問題明確)

from r in table.AsEnumerable() 
group r by new { 
    Category = r.Field<string>("Category"), 
    Description = r.Field<string>("Description") 
} into g 
select new { 
    Category = g.Key.Category, 
    Description = g.Key.Description, 
    CurrentHours = g.Sum(x => x.Field<int>("CurrentHours"), 
    CTDHours = g.Sum(x => x.Field<int>("CurrentHours") + x.Field<int>("CTDHours")) 
} 

from r in context.Table 
group r by new { 
    r.Category, 
    r.Description 
} into g 
select new { 
    g.Key.Category, 
    g.Key.Description, 
    CurrentHours = g.Sum(x => x.CurrentHours), 
    CTDHours = g.Sum(x => x.CTDHours + x.CurrentHours) 
} 
+0

工作。非常感謝。順便說一句,你是如何讓我的專欄排得如此完美的?我試圖弄清楚並失敗。 – John

+2

@John我選擇了表格並將其格式化爲代碼(它保留了空格):) –

+2

@SergeyBerezovskiy謝謝你給出兩個版本,**真的很棒** :) –

0

你需要總結CurrentHoursCTDhours,讓 -

select new { 
    ... 
    CTDHours = g.Sum(x => x.Field<int>("CTDHours") + g.Sum(x => x.Field<int>("CurrentHours") 
}