c# - using dt.AsEnumerable().Sum for columns having string/null value -


i using following way total of column datatable

string total = dt.asenumerable().sum(x => x.field<decimal>("col1")).tostring(); 

this works fine when values of col1 number.

my question is- lets consider if 1 value of col1 string or null or else other number, above code throw error obviously.

is there way check whether value number , use '0' instead if value not number.

i tried -

string total = dt.asenumerable().sum(x =>  x.field<decimal>("col1") int ? x.field<decimal>("col1") : 0).tostring(); 

but not sure if correct way.

please help

if it's not decimal string invalidcastexception in field<t> method. have know type is.

i assume col1 can null, field<t> supports nullable types:

decimal total = dt.asenumerable()  .sum(r => r.field<decimal?>("col1") ?? 0); 

or without replacing null 0:

decimal? total = dt.asenumerable()  .sum(r => r.field<decimal?>("col1")); // use total.hasvalue , total.value 

presuming string, use decimal.tryparse:

decimal d = 0; decimal total = dt.asenumerable()  .where(r => decimal.tryparse(r.field<string>("col1"), out d))  .sum(r => d); 

if don't know type use object.tostring:

decimal total = dt.asenumerable()  .where(r => !r.isnull("col1") && decimal.tryparse(r["col1"].tostring(), out d))  .sum(r => d); 

apart that, why store converted number again in string variable?


Comments

Popular posts from this blog

Android layout hidden on keyboard show -

google app engine - 403 Forbidden POST - Flask WTForms -

c - Why would PK11_GenerateRandom() return an error -8023? -