datatable的数据转置

没有具体测试过,5w条数据在i5机器上大概是1.3~2s左右,但是个人感觉就是在处理数据库的分页或者是写条件的时候会有一些麻烦,不如使用数据库分页!

但是这种方法不失为一种思路

private void Form1_Load(object sender, EventArgs e)
{
#region 
DataTable dt = new DataTable();
dt.Columns.Add("name");
dt.Columns.Add("name2");
dt.Columns.Add("type");
dt.Columns.Add("count");

Random ran3 = new Random();
Random ran = new Random();
Random ran2 = new Random();

Stopwatch stopWatch = new Stopwatch();
stopWatch.Start();
DataRow dr ;
for (int i = 0; i < 50000; i++)
{
int k3 = ran3.Next(1, 2000);
int k=ran.Next(1, 13);
int c=ran2.Next(50, 100);

dr = dt.NewRow();

dr["name"] = "n"+k3.ToString();
dr["name2"] = "n2" + k3.ToString();
dr["type"] = "t"+k.ToString();
dr["count"] = "co"+c.ToString();
dt.Rows.Add(dr);
}
stopWatch.Stop();
Console.WriteLine(stopWatch.ElapsedMilliseconds.ToString());

#endregion
stopWatch.Restart();
DataTable dt2=getDt(dt, "type", "count","name","name2");
stopWatch.Stop();
Console.WriteLine(stopWatch.ElapsedMilliseconds.ToString());
this.dataGridView1.DataSource = dt2;
}
/// <summary>
///
/// </summary>
/// <param name="dtsource">数据源</param>
/// <param name="colName">需要转置为列名的列 如city列</param>
/// <param name="dataName">需要转置的数据列 如count列</param>
/// <param name="val">其他可区分列 如name2列</param>
/// <returns></returns>
DataTable getDt(DataTable dtsource, string colName, string dataName, params string[] fileds)
{
DataTable dt = new DataTable();

DataTable newTable = dtsource.DefaultView.ToTable(true, fileds);

DataTable dtcol = dtsource.DefaultView.ToTable(true, colName);

foreach (DataRow item in dtcol.Rows)
{
newTable.Columns.Add(item[0].ToString());
}

for (int i = 0; i < newTable.Rows.Count; i++)
{
string strSel1 = "1=1 ";
for (int k = 0; k < fileds.Length; k++)//处理开头的数据
{
string rowname = newTable.Rows[i][k].ToString();
newTable.Rows[i][k] = rowname;
strSel1 += string.Format(" and {0}='{1}'",fileds[k],rowname);
}

for (int j = fileds.Length; j < newTable.Columns.Count; j++)
{
string cname = newTable.Columns[j].ColumnName;

string strSel2 = string.Format("{0}='{1}'",colName,cname);

DataRow[] dn = dtsource.Select(strSel1 + " and " + strSel2);

if (dn!=null&&dn.Length>0)
{
newTable.Rows[i][j] = dn[0][dataName].ToString();
}
}
}

return newTable;
}

 
上一篇:CF 274B Zero Tree 树形DP


下一篇:jQuery的工作原理