Average extension method for Datatable

Niladri.Biswas
Posted by Niladri.Biswas under C# category on | Points: 40 | Views : 709
/// <summary>
/// Average of data rows in a datatable
/// </summary>
/// <param name="dt"></param>
/// <param name="insertAt"></param>
/// <param name="columnName"></param>
/// <returns></returns>
public static DataTable Average(this DataTable dt, int insertAt, string columnName)
{
DataRow dr;
List<object> lstColumnResult = new List<object>();
int res = 0;
int rowCount = dt.Rows.Count;

//Add the first column name
lstColumnResult.Add(columnName);

for (int i = 1; i < dt.Columns.Count; i++)
{
for (int row = 0; row < dt.Rows.Count; row++)
{

res = res + Convert.ToInt32(dt.Rows[row][i]);
}

lstColumnResult.Add(res / rowCount);
res = 1;
}
//add a new data row
dr = dt.NewRow();
dr.ItemArray = lstColumnResult.ToArray();
//insert the row at the position specified
dt.Rows.InsertAt(dr, insertAt);
//accept the changes
dt.AcceptChanges();
return dt;
}

Comments or Responses

Login to post response