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;
}

 

 

 

转载于:https://www.cnblogs.com/lizhaoduo/p/3940600.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值