c# - Linq query is not executing properly -
i'am trying sum datatable column's in linq. when program running foreach loop not executing. checked milion times if column names equal datatable.
resultdatatable.columns.add("user id"); resultdatatable.columns.add("amount"); resultdatatable.columns.add("order number"); var query = row in result.asenumerable() group row row.field<string>("user id") grp select new { id = grp.key, sum = grp.sum(r => r.field<int>("amount")), sum2 = grp.sum(r => r.field<int>("order number")) }; foreach(var item in query) { resultdatatable.rows.add(item.id, item.sum, item.sum2); }
the result datatable 3 columns. first 1 name , last name, second 1 number , third number also.
any ideas why doesn't work?
i assume have created source table in same way destination table, adding columns manually. guess contained string
-columns instead of int
columns. note default string
.
so following creates , adds 3 columns of type string:
resultdatatable.columns.add("user id"); resultdatatable.columns.add("amount"); resultdatatable.columns.add("order number");
instead use overload:
resultdatatable.columns.add("user id"); resultdatatable.columns.add("amount", typeof(int)); resultdatatable.columns.add("order number", typeof(int));
why important? because otherwise can't use sum = grp.sum(r => r.field<int>("amount"))
since column's type isn't int
string
, you'll runtime invalidcastexception
in field
@ foreach
. maybe have empty try...catch
somewhere swallows exception , should avoided.
a better way create table , columns, if destination table has same columns use datatable.clone
:
datatable resultdatatable = result.clone(); // same columns empty
Comments
Post a Comment