Divide extension method for Datatable

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

//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++)
{
if (row == 0)
{
res = Convert.ToDouble(dt.Rows[row][i]);
}
else
{
res = res / Convert.ToDouble(dt.Rows[row][i]);
}
}

lstColumnResult.Add(res);
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