2014-01-09 83 views
0

我試圖在DataSet上執行兩個DataTable此查詢我怎樣才能在總保持空(DBNull的)在LINQ查詢

SELECT Totals.accCategory, Totals.ID, Totals.Account, Sum(Totals.Jan) AS Jan FROM (SELECT * FROM Allocated UNION SELECT * FROM Spent) AS Totals GROUP BY Totals.accCategory, Totals.ID, Totals.Account 

,因爲他們在代碼(在內存中)產生到DataSet我因此需要使用LINQ:

Dim t = (From totals In (allocated.AsEnumerable.Union(spent.AsEnumerable)) _ 
      Group totals By accCategory = totals.Item("accCategory"), ID = totals.Item("ID"), Account = totals.Item("Account") _ 
      Into g = Group _ 
      Select New With {Key .accCategory = accCategory, Key .ID = ID, Key .Account = Account, Key .Jan = g.Sum(Function(totals) Totals.Item("Jan"))}).ToList 

由於存在一些沒有記錄求和的實例,因此失敗。 Access查詢返回一個空單元格 - 這正是我想要的。我可以用If(IsDbNull(totals.Item("Jan")),0,totals.Item("Jan"))使LINQ發言的工作,但後來我得到0.00如果總爲零(這是正確的),而且如果沒有項目總結(我不希望)

我已經試過Select New With {Key .accCategory = accCategory, Key .ID = ID, Key .Account = Account, Key .Jan = g.Sum(Function(totals) DirectCast(totals.Item("Jan"), Nullable(Of Decimal)))}).ToList這也不起作用。

我該如何製作.Jan a Nullable(十進制)並接受DBNull作爲值?

感謝 安迪

+0

-1沒有閱讀,代碼格式不正確。 – Aron

+0

不知道你在問什麼,但'DefaultIfEmpty'可能是你想要的。 – Neolisk

+0

阿隆 - 坦率地說,這很粗魯。代碼被標記爲代碼。在這裏其他人都很有幫助時感到羞愧。 Neolisk - 謝謝,看起來。 –

回答

1

明白了!

Dim t = (From totals In (allocated.AsEnumerable.Union(spent.AsEnumerable)) _ 
      Group totals By accCategory = totals.Item("accCategory"), ID = totals.Item("ID"), Account = totals.Item("Account") _ 
      Into g = Group _ 
      Select New With {Key .accCategory = accCategory, Key .ID = ID, Key .Account = Account, Key .Jan = If(g.AsQueryable.Any(Function(totals) totals.Field(Of Nullable(Of Decimal))("Jan").HasValue), g.AsQueryable.Sum(Function(totals) totals.Field(Of Nullable(Of Decimal))("Jan")), Nothing)}).ToList 
+0

完美無缺! :) – theB3RV