如何使用c#安排数据表

本文关键字:数据表 何使用 | 更新日期: 2023-09-27 18:06:11

我正在动态构建数据表,格式如下,

DataTable dt = new DataTable();
DataColumn dc;
dc = new DataColumn();
dc.ColumnName = "Question";
dt.Columns.Add(dc);
dc = new DataColumn();
dc.ColumnName = "User1";
dt.Columns.Add(dc);
dc = new DataColumn();
dc.ColumnName = "User2";
dt.Columns.Add(dc);
dr["Question"] = "2D";
dr["User1"] = "1";
dr["Question"] = "3D";
dr["User1"] = "4";
dr["Question"] = "2D";
dr["User2"] = "2";
dr["Question"] = "3D";
dr["User2"] = "5";

我该如何安排呢?

DataTable dt = new DataTable();
DataColumn dc;
dc = new DataColumn();
dc.ColumnName = "Question";
dt.Columns.Add(dc);
dc = new DataColumn();
dc.ColumnName = "User1";
dt.Columns.Add(dc);
dc = new DataColumn();
dc.ColumnName = "User2";
dt.Columns.Add(dc);
dr["Question"] = "2D";
dr["User1"] = "1";
dr["User2"] = "2";
dr["Question"] = "3D";
dr["User1"] = "4";
dr["User2"] = "5";

如何使用c#安排数据表

您可以使linq交叉连接并过滤它为列表(您可以将列表绑定到您的msChart)

var result = (from dr1 in dt.Select()
                  join dr2 in dt.Select() on dr1["Question"].ToString() equals dr2["Question"].ToString()
                  select new { q = dr1["question"], u1 = dr1["User1"], u2 = dr2["User2"] }
                 ).Where(row => row.u1.ToString().Length > 0 && row.u2.ToString().Length > 0).ToList();

您可以使用类似的代码;

DataRow dr = dt.NewRow();
dr["Question"] = "2D";
dr["User1"] = "1";
dr["User2"] = "2";
dr = dt.NewRow();
dr["Question"] = "3D";
dr["User1"] = "4";
dr["User2"] = "5";

假设dr是DataRow类型的变量,通过调用DataTable方法NewRow获得,那么只需一行就可以将值添加到行ItemArray属性中。
当然,您需要绝对确定列的顺序和类型

    DataRow dr = dt.NewRow();
    dr.ItemArray = new object[] {"Q1", "1", "2"};
    dt.Rows.Add(dr);
    dr = dt.NewRow();
    dr.ItemArray = new object[] {"Q2", "3", "4"};
    dt.Rows.Add(dr);