C# .NET - Checking for NULL values while computing the SUM of a dataset column.

Asked By Charvi on 17-Dec-14 10:33 PM


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,
Robbe Morris replied to Charvi on 18-Dec-14 08:12 AM

You may also need to write a little function that converts an empty string to zero.
Gorav Handa replied to Charvi on 05-Jan-15 06:05 AM
var totalABC = ds.Tables[0].AsEnumerable().Sum(x => Convert.ToDecimal(x["ABC"] == DBNull.Value ? 0 : x["ABC"]));

You can decorate it more by avoiding x["ABC"] two times in expression.