码迷,mamicode.com
首页 > 其他好文 > 详细

datatable的数据转置

时间:2014-08-28 00:47:48      阅读:229      评论:0      收藏:0      [点我收藏+]

标签:datagridview   style   blog   color   os   使用   io   for   ar   

没有具体测试过,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;
}

 

 

 

datatable的数据转置

标签:datagridview   style   blog   color   os   使用   io   for   ar   

原文地址:http://www.cnblogs.com/lizhaoduo/p/3940600.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!