## 2 replies

Last post Aug 10, 2011 10:11 PM by Decker Dong - MSFT

• digish

Member

184 Points

750 Posts

### how to find the average of columns ina datatable

Hi,

how to find the average of columns ina datatable. The columns are string. but the content is numerical.

• rajdeep.in

Member

440 Points

99 Posts

### Re: how to find the average of columns ina datatable

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));

DataColumn fsal = new DataColumn("FSal", typeof(float));
fsal.Expression = "Sal";

DataRow dr = dt.NewRow();
dr[0] = "3000";

DataRow dr2 = dt.NewRow();
dr2[0] = "6000";

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 if this post helps you.
• Decker Dong...

All-Star

94130 Points

18109 Posts

### Re: how to find the average of columns ina datatable

Aug 10, 2011 10:11 PM|Decker Dong - MSFT|LINK

#### digish

how to find the average of columns ina datatable. The columns are string. but the content is numerical

Another way is to use Average——the exnteded method of LINQ——

```    public class MainTest
{
static void Main(string[] args)
{
DataTable dt = new DataTable();