【问题标题】:Datatable.merge like joinDatatable.merge 像连接
【发布时间】:2016-06-27 06:57:18
【问题描述】:

我有两个这样的DataTables

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

dt1:

dt2:

我需要像这样合并两个DataTables 并设置为GridView

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

但是得到这样的输出:

我怎样才能像这样合并?

【问题讨论】:

    标签: c# datatable


    【解决方案1】:

    您需要添加以下行:

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

    【讨论】:

    • 出现这样的错误:这些列当前没有唯一值。"} System.Exception {System.ArgumentException}
    • 我没有唯一的列。我需要按 1. 和 2. 列加入。
    • 然后设置col 0和col 1为主键
    • 是的!当我将 col0 和 col1 设置为主键时,它就起作用了。谢谢。
    • @Ricardo 我更新了我的答案,如果您在正确显示数据时遇到问题,请尝试使用 dt1.Merge(dt2, false); 而不是 dt1.Merge(dt2, true, MissingSchemaAction.Add);
    【解决方案2】:

    你也可以用 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
                    //...
                 };
    

    【讨论】:

      猜你喜欢
      • 2013-10-22
      • 1970-01-01
      • 1970-01-01
      • 2016-04-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-02-22
      相关资源
      最近更新 更多