如何使用C#安排数据表

时间:2013-03-28 10:33:29

标签: c# datatable

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

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

3 个答案:

答案 0 :(得分:1)

您可以使用与此类似的代码;

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

答案 1 :(得分:1)

假设dr是调用DataTable方法NewRow获得的DataRow类型的变量,那么您可以在一行中将值添加到行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);

答案 2 :(得分:1)

你可以使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();