2013-06-24 26 views
0

我在數據表中使用VB中的LINQ來過濾我的結果。GroupBy和數據表上的總和

m_oDataTable.Columns.Add("Name1", GetType(String)) 
m_oDataTable.Columns.Add("Name2", GetType(String)) 
m_oDataTable.Columns.Add("Time", GetType(Double)) 

我試圖通過Name1Name2基於用戶選擇來過濾數據表。

groupBy = "Name1" 
'groupBy = "Name2" 

我我的分組數據,但我無法Sum所需的字段。

Dim test = From tab In m_oDataTable.AsEnumerable() 
      Group tab By groupDt = tab.Field(Of String)(groupBy) Into Group 
      Select Group 

'Getting Error 
Dim test2 = From tab In m_oDataTable.AsEnumerable() 
      Group tab By groupDt = tab.Field(Of String)(groupBy) Into Group 
      Select New With 
      { 
      .Grp = Key, ' Error in this line(Key is a type, cannot be used as a expression) 
      .Sum = Group.Sum(Function(r) Double.Parse(r.Item("Time").ToString())) 
      } 

我在c#中試過並得到了期望的結果。但有沒有運氣與VB :(

var test = from tab in m_oDataTable.AsEnumerable() 
      group tab by tab.Field<string>(groupBy) 
       into groupDt 
       select new 
       { 
        Group = groupDt.Key, 
        Sum = groupDt.Sum(r => double.Parse(r["Time"].ToString())) 
       }; 

如何在VB中實現這一目標?

回答

1

不是100%肯定爲什麼,但VB.Net不支持。重點對查詢表達式語法。實際上,你定義的關鍵你試圖使用一個未定義的變量「Key」,而是你需要使用它們在你的查詢中定義的鍵(groupDt)。

更改一個小行,它應該工作。 ..

Select New With 
       { 
       .Grp = groupDt, 
       .Sum = Group.Sum(Function(r) Double.Parse(r.Item("Time").ToString())) 
       } 

或者你可以使用流利的語法:

Dim test2 = Table.AsEnumerable().GroupBy(Function(row) row.Item("Name1")).Select(Function(group) New With {.Grp = group.Key, .Sum = group.Sum(Function(r) Double.Parse(r.Item("Time").ToString()))})