Original table
Swapped table
As you can see columns are rows now but there is first row added (this is what the function I found did). So if you want to have table like this:
You can delete first row and change ordering others rows or you can use this function :) :
public DataSet flipDataSet(DataSet dataSet, string columnToXName, bool showColumnX)
{
DataSet ds = new DataSet();
DataTable table = new DataTable();
//Loop through all tables in dataset
//if flipping all tables is not needed the table should be specify
foreach (DataTable dt in dataSet.Tables)
{
//creating a new columns
for (int i = 0; i <= dt.Rows.Count; i++)
{
if (i != 0)
table.Columns.Add(dt.Rows[i - 1][columnToXName].ToString());
else
table.Columns.Add(columnToXName);
}
//filling columns
DataRow r;
for (int k = 0; k < dt.Columns.Count; k++)
{
if (k != dt.Columns.IndexOf(columnToXName))
{
r = table.NewRow();
r[0] = dt.Columns[k].ToString();
for (int j = 1; j <= dt.Rows.Count; j++)
r[j] = dt.Rows[j - 1][k];
table.Rows.Add(r);
}
}
}
if (!showColumnX)
table.Columns.Remove(columnToXName);
ds.Tables.Add(table);
return ds;
}
Maybe it can safe some time to somebody ;)



No comments:
Post a Comment