Datatable.merge喜欢加入

时间:2016-06-27 06:57:18

标签: c# datatable

我有两个DataTables这样:

DataTable dt1 = new DataTable();
DataTable dt2 = new DataTable();

dt1

enter image description here

dt2

enter image description here

我需要合并两个DataTables并设置为GridView,如下所示:

dt1.Merge(dt2, true, MissingSchemaAction.Add);
GridView1.DataSource = dt1;
GridView1.DataBind();

但是得到这样的输出:

enter image description here

我该如何合并?

enter image description here

2 个答案:

答案 0 :(得分:5)

您需要添加以下行:

dt1.PrimaryKey = new[] { dt1.Columns[0], dt1.Columns[1] };
dt2.PrimaryKey = new[] { dt2.Columns[0], dt2.Columns[1] };

答案 1 :(得分:1)

您也可以使用LINQ:

var result = from a in dt1.AsEnumerable()
             join b in dt2.AsEnumerable() on new { C = a.Field<string>("CAR"),
             M = a.Field<string>("MODEL") } equals new { C = b.Field<string>("CAR"), 
             M = b.Field<string>("MODEL") } 
             select
             {
                CAR = a.Field<string>("CAR"),
                MODEL = a.Field<string>("MODEL"),
                DATE1 = a.Field<string>("DATE1") // You should write your type
                //...
             };