Vb.net 在LINQ查询中如何在Sum中保留Null(DBNull)

Vb.net 在LINQ查询中如何在Sum中保留Null(DBNull),vb.net,linq,null,sum,Vb.net,Linq,Null,Sum,我试图在数据集中的两个数据表上执行此查询 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 由于它们是在数据集中的代码(内存中)中生成的,因此我需要使

我试图在数据集中的两个数据表上执行此查询

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
由于它们是在数据集中的代码(内存中)中生成的,因此我需要使用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

我试过
用{Key.acccegority=acccegority,Key.ID=ID,Key.Account=Account,Key.Jan=g.Sum(函数(totals)DirectCast(totals.Item(“Jan”),Nullable(Of Decimal))}选择新建。ToList
也不起作用

如何将.Jan设为可空(十进制)并接受DBNull作为值

谢谢 安迪明白了

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

-我没读过,代码格式很差。不确定你在问什么,但
DefaultIfEmpty
可能是你想要的。阿隆-坦白说,这太粗鲁了。代码被标记为代码。真可惜,这里的其他人都这么乐于助人。Neolisk-谢谢,我会看看。我不认为我需要
DefaultIfEmpty
,我想保留空值。我想这可能与你有关,但我搞不懂。谢谢。这
选择新建,其中{Key.acccegority=acccegority,Key.ID=ID,Key.Account=Account,Key.Jan=g.Sum(函数(总计为数据行)可为空(十进制)不返回任何内容(结束函数)}).ToList
似乎使用了正确的总和类型-但当我强制它为
Nothing
并检查表时,它仍然显示0D。