The following LINQ statement sums the values that can be converted into an
int
:
DataTable dt = ...
...
string col = "Price";
int sum = dt.AsEnumerable()
.Aggregate(0,(n, r)=>
{
int v;
return int.TryParse((r[col] as string) ?? string.Empty, out v)
? n + v
: n;
}
);
Or a bit easier to read:
DataTable dt = ...
...
int sum = dt.AsEnumerable().Aggregate(0,(n,r)=>PriceField(r)+n);
...
static int PriceField(DataRow r)
{
int v;
return int.TryParse((r["Price"] as string) ?? string.Empty, out v) ? v : 0;
}
Or a further alternative:
DataTable dt = ...
...
int sum = dt.AsEnumerable().Aggregate(0,SumPriceField);
...
static int SumPriceField(int n, DataRow r)
{
int v;
return int.TryParse((r["Price"] as string) ?? string.Empty, out v) ? n + v : n;
}
Cheers
Andi