You can use add additional float column and user datacolumn.expression to map with your string column and then calculate average on float column. A sample is here,
DataTable dt = new DataTable();
DataColumn sal = new DataColumn("Sal", typeof(string));
dt.Columns.Add(sal);
DataColumn fsal = new DataColumn("FSal", typeof(float));
fsal.Expression = "Sal";
dt.Columns.Add(fsal);
DataRow dr = dt.NewRow();
dr[0] = "3000";
dt.Rows.Add(dr);
DataRow dr2 = dt.NewRow();
dr2[0] = "6000";
dt.Rows.Add(dr2);
float avgsal = (float)dt.Compute("Avg(FSal)", "");
Console.WriteLine("sal: {0}", avgsal);
Important: It is automatically converting the string to float. So if you have anything other than "Numberical" (e.g. alpahabets, special chars, null etc.) on the string column you'll get runtime exception.
Hope this helps. Let me know how it goes.
Best Regards,
Rajdeep Das
Please Mark as Answered if this post helps you.Your 'Mark' will help other people having similar problem.
rajdeep.in
Member
644 Points
102 Posts
Re: how to find the average of columns ina datatable
Aug 08, 2011 04:03 PM|LINK
Hi,
You can use add additional float column and user datacolumn.expression to map with your string column and then calculate average on float column. A sample is here,
DataTable dt = new DataTable(); DataColumn sal = new DataColumn("Sal", typeof(string)); dt.Columns.Add(sal); DataColumn fsal = new DataColumn("FSal", typeof(float)); fsal.Expression = "Sal"; dt.Columns.Add(fsal); DataRow dr = dt.NewRow(); dr[0] = "3000"; dt.Rows.Add(dr); DataRow dr2 = dt.NewRow(); dr2[0] = "6000"; dt.Rows.Add(dr2); float avgsal = (float)dt.Compute("Avg(FSal)", ""); Console.WriteLine("sal: {0}", avgsal);Important: It is automatically converting the string to float. So if you have anything other than "Numberical" (e.g. alpahabets, special chars, null etc.) on the string column you'll get runtime exception.
Hope this helps. Let me know how it goes.
Rajdeep Das
Please Mark as Answered if this post helps you.Your 'Mark' will help other people having similar problem.