Using DataTable.Compute filter on null entries

717 Views Asked by At

Suppose that there is a DataTable dt of type double with the columns "x","y","z" in C#.

While values are filled into dt, it certainly occurs that only two dimensions are assigned a being assigned which intentionally leaves the third vacant with DBNull.Value.

When computing the average for a dimension with a filter according to Transact-SQL syntax things work properly:

X = (double)dt.Compute("Avg([x])", "x IS NOT NULL");

However, the following results in System.InvalidCastException: 'Specified cast is not valid.'

sx = (double)dt.Compute("StDev([x])", "x IS NOT NULL");

This would be highly convenient compared to a seperate method to calculate the standard deviation . And even at this point there is trouble when converting a column with null values into a List:

List<double> xValues = dt.Rows.OfType<DataRow>().Select(dr => dt.Field<double>("x")).ToList();

System.InvalidCastException: 'Cannot cast DBNull.Value to type 'System.Double'. Please use a nullable type.'

Any suggestions on handling this situation be it with null-conditionals or suggestions on the filter are highly appreciated.

0

There are 0 best solutions below