欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

C#中DataTable实现行列转换的方法

程序员文章站 2022-07-01 17:18:39
本文实例讲述了c#中datatable实现行列转换的方法。分享给大家供大家参考。具体实现方法如下: protected void page_load(object...

本文实例讲述了c#中datatable实现行列转换的方法。分享给大家供大家参考。具体实现方法如下:

protected void page_load(object sender, eventargs e)
{
  if (!ispostback)
  {
   datatable tt = getcrosstable(createdt());
   gridview1.datasource = tt;
   gridview1.databind();
  }
}
//创建datatable
protected datatable createdt()
{
  datatable tbldatas = new datatable("datas");
  //数据列
  tbldatas.columns.add("姓名", type.gettype("system.string"));
  tbldatas.columns.add("科目", type.gettype("system.string"));
  tbldatas.columns.add("分数", type.gettype("system.int32"));
  tbldatas.rows.add(new object[] { "张三", "语文", 89 });
  tbldatas.rows.add(new object[] { "张三", "数学", 90 });
  tbldatas.rows.add(new object[] { "张三", "英语", 79 });
  tbldatas.rows.add(new object[] { "张三", "地理", 70 });
  tbldatas.rows.add(new object[] { "张三", "生物", 95 });
  tbldatas.rows.add(new object[] { "李四", "语文", 87 });
  tbldatas.rows.add(new object[] { "李四", "英语", 86 });
  tbldatas.rows.add(new object[] { "李四", "地理", 82 });
  tbldatas.rows.add(new object[] { "王五", "语文", 81 });
  tbldatas.rows.add(new object[] { "王五", "数学", 70 });
  tbldatas.rows.add(new object[] { "王五", "英语", 88 });
  tbldatas.rows.add(new object[] { "王五", "生物", 96 });
  return tbldatas;
}
/// <summary>
/// 将datatable的第二列的值转化为列
//(即将原来的行表,转化成交叉表,没有对应值则默认"0")
/// </summary>
/// <param name="dt">必须三列,第三列为值</param>
/// <returns></returns>
public static datatable getcrosstable(datatable dt)
{
  if (dt == null || dt.columns.count != 3 || dt.rows.count == 0)
  {
   return dt;
  }
  else
  {
   datatable result = new datatable();
   result.columns.add(dt.columns[0].columnname);
   datatable dtcolumns = dt.defaultview.totable("dtcolumns", true, dt.columns[1].columnname);
   for (int i = 0; i < dtcolumns.rows.count; i++)
   {
    string colname;
    if (dtcolumns.rows[1][0] is datetime)
    {
     colname = convert.todatetime(dtcolumns.rows[i][0]).tostring();
    }
    else
    {
     colname = dtcolumns.rows[i][0].tostring();
    }
    result.columns.add(colname);
    result.columns[i + 1].defaultvalue = "0";
   }
   datarow drnew = result.newrow();
   drnew[0] = dt.rows[0][0];
   string rowname = drnew[0].tostring();
   foreach (datarow dr in dt.rows)
   {
    string colname = dr[1].tostring();
    double dvalue = convert.todouble(dr[2]);
    if (dr[0].tostring().equals(rowname, stringcomparison.currentcultureignorecase))
    {
     drnew[colname] = dvalue.tostring();
    }
    else
    {
     result.rows.add(drnew);
     drnew = result.newrow();
     drnew[0] = dr[0];
     rowname = drnew[0].tostring();
     drnew[colname] = dvalue.tostring();
    }
   }
   result.rows.add(drnew);
   return result;
  }
}

希望本文所述对大家的c#程序设计有所帮助。