Reputation: 2180
I am trying to sum numeric values from a datatable using linq but because there are also null values in column UniteDispo
I am getting an error:
Cannot cast DBNull.Value to type 'Decimal'. Please use a nullable type.
This is my code:
Dim query2 = (From order In tabDispoAnnee.AsEnumerable() _
Where order.Field(Of Integer)("code_part") = tab.Rows(i).Item("code_part") And order.Field(Of Integer)("CodeTypeBien") = tab.Rows(i).Item("CodeTypeBien") _
Group order By order!code_part, order!CodeTypeBien _
Into unit = Sum(CDec(order("UniteDispo"))), ca = Sum(CDec(order("CADispo"))) _
Select unit, ca).ToList
What is the proper syntax to overcome this error?
Upvotes: 2
Views: 857
Reputation: 15772
Add a Where
clause to filter out records with NULL
value. Try this
Dim query2 = (From order In tabDispoAnnee.AsEnumerable() _
Where order.Field(Of Integer)("code_part") = tab.Rows(i).Item("code_part") _
And order.Field(Of Integer)("CodeTypeBien") = tab.Rows(i).Item("CodeTypeBien") _
And order.Field(Of Integer?)("UniteDispo").HasValue _
And order.Field(Of Double?)("CADispo").HasValue _
Group order By order!code_part, order!CodeTypeBien _
Into unit = Sum(CDec(order("UniteDispo"))), ca = Sum(CDec(order("CADispo"))) _
Select unit, ca).ToList
Upvotes: 1