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:
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:
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