Click here to Skip to main content
15,909,051 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
Hi,

I am trying to compute the SUM total of a particular column in my DataSet.

I am using the below code to achieve it.

var totalABC = ds.Tables[0].AsEnumerable().SUM(x => Convert.ToDecimal(x["ABC"]));

where ABC is the column that I am summing up.

However, at runtime I get an error saying :

Cannot convert System.DBNull to decimal type. How do I check for Nulls in the above code & only convert the non-Null values to decimal?


Thanks in advance,
Aakar.
Posted

C#
decimal total = ds.Tables[0].AsEnumerable()
 .Sum(r => r.Field<decimal?>("ABC") ?? 0);

or
C#
decimal? total = ds.Tables[0].AsEnumerable()
 .Sum(r => r.Field<decimal?>("ABC"));

without Field extension method
C#
var total = ds.Tables[0].Compute("Sum(ABC)", "");

or
C#
var totalABC = ds.Tables[0].AsEnumerable().Sum(x => x.IsNull("ABC")?0.0m:Convert.ToDecimal(x["ABC"]));
 
Share this answer
 
v3
Comments
aakar 18-Dec-14 3:25am    
I tried the two solutions with the field extension method, but I am getting a "Specified Cast is not Valid" error message.
DamithSL 18-Dec-14 3:26am    
what is the database column type?
aakar 18-Dec-14 3:42am    
The DB datatype is float
DamithSL 18-Dec-14 3:46am    
then you need to change decimal to double
you should have told these information when you ask the question. anyway what is your database ?
Maciej Los 18-Dec-14 5:05am    
+5!
In addition to solution 1...

I just realized that using above queries/statements together with Average function could be the reason of false results. Why?

Let's say, the data stored in the datatable are: {5, DBNull.Value, 42, 7, DBNull.Value}
When you execute command:
C#
total = dt.AsEnumerable().Average(x=>x["ABC"]==DBNull.Value ? 0 : (double)x["ABC"]);

you'll get: 10.8 as a result.
But when you execute command like:
C#
total = dt.AsEnumerable().Where(x=>x["ABC"]!=DBNull.Value).Average(x=>(double)x["ABC"]);

you'll get 18 as result.

The explanation is quite simple: the sum is the same (54), but the count of items is differ.
In first case, null values are replaced with 0 (zeros), so the count of items is equal five. 54/5=10.8
In second case, null values are ignored, so the count of items is equal three. 54/3=18
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900