2014-01-09 124 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