如何将两个数据表dt1 = 2列,dt2 = 3列添加到一个数据表dt3 = 5列中

时间:2016-08-04 05:06:32

标签: c# datatable

如何添加两个数据表?

(dt2=address,cityname) 

(dt3=name,phone_number,address,cityname)

结果:

    <div ng-repeat="x in list">
        <button ng-click="callCustomFn(x.text)">
         {{x.text}}
        </button>
    </div>

2 个答案:

答案 0 :(得分:0)

Ruben,你需要一些主键来组合两个表,除非你100%确定两个数据表具有相同的行数并且它们将始终以正确的顺序存储。

回答了类似的问题,链接是:Combining n DataTables into a Single DataTable

以下是所提供链接的内容: &#34;该表在Merge之后具有重复的主键,因为没有定义主键。所以要么指定PK,要么在这里尝试这种方法,我从头开始编写(所以它没有经过真正的测试):

public static DataTable MergeAll(this IList<DataTable> tables, String primaryKeyColumn)
{
   if (!tables.Any())
       throw new ArgumentException("Tables must not be empty", "tables");
   if(primaryKeyColumn != null)
       foreach(DataTable t in tables)
        if(!t.Columns.Contains(primaryKeyColumn))
            throw new ArgumentException("All tables must have the specified primarykey column " + primaryKeyColumn, "primaryKeyColumn");

   if(tables.Count == 1)
       return tables[0];

   DataTable table = new DataTable("TblUnion");
   table.BeginLoadData(); // Turns off notifications, index maintenance, and constraints while loading data
   foreach (DataTable t in tables)
   {
       table.Merge(t); // same as table.Merge(t, false, MissingSchemaAction.Add);
   }
   table.EndLoadData();

   if (primaryKeyColumn != null)
   {
       // since we might have no real primary keys defined, the rows now might have repeating fields
       // so now we're going to "join" these rows ...
       var pkGroups = table.AsEnumerable()
           .GroupBy(r => r[primaryKeyColumn]);
       var dupGroups = pkGroups.Where(g => g.Count() > 1);
       foreach (var grpDup in dupGroups)
       { 
           // use first row and modify it
           DataRow firstRow = grpDup.First();
           foreach (DataColumn c in table.Columns)
           {
               if (firstRow.IsNull(c))
               {
                   DataRow firstNotNullRow = grpDup.Skip(1).FirstOrDefault(r => !r.IsNull(c));
                   if (firstNotNullRow != null)
                       firstRow[c] = firstNotNullRow[c];
               }
           }
           // remove all but first row
           var rowsToRemove = grpDup.Skip(1);
           foreach(DataRow rowToRemove in rowsToRemove)
               table.Rows.Remove(rowToRemove);
       }
   }

   return table;
}

您可以这样称呼它:

var tables = new[] { tblA, tblB, tblC };
DataTable TblUnion = tables.MergeAll("c1");

使用此示例数据:

var tblA = new DataTable();
tblA.Columns.Add("c1", typeof(int));
tblA.Columns.Add("c2", typeof(int));
tblA.Columns.Add("c3", typeof(string));
tblA.Columns.Add("c4", typeof(char));

var tblB = new DataTable();
tblB.Columns.Add("c1", typeof(int));
tblB.Columns.Add("c5", typeof(int));
tblB.Columns.Add("c6", typeof(string));
tblB.Columns.Add("c7", typeof(char));

var tblC = new DataTable();
tblC.Columns.Add("c1", typeof(int));
tblC.Columns.Add("c8", typeof(int));
tblC.Columns.Add("c9", typeof(string));
tblC.Columns.Add("c10", typeof(char));

tblA.Rows.Add(1, 8500, "abc", 'A');
tblA.Rows.Add(2, 950, "cde", 'B');
tblA.Rows.Add(3, 150, "efg", 'C');
tblA.Rows.Add(4, 850, "ghi", 'D');
tblA.Rows.Add(5, 50, "ijk", 'E');

tblB.Rows.Add(1, 7500, "klm", 'F');
tblB.Rows.Add(2, 900, "mno", 'G');
tblB.Rows.Add(3, 150, "opq", 'H');
tblB.Rows.Add(4, 850, "qrs", 'I');
tblB.Rows.Add(5, 50, "stu", 'J');

tblC.Rows.Add(1, 7500, "uvw", 'K');
tblC.Rows.Add(2, 900, "wxy", 'L');
tblC.Rows.Add(3, 150, "yza", 'M');
tblC.Rows.Add(4, 850, "ABC", 'N');
tblC.Rows.Add(5, 50, "CDE", 'O');

在MergeAll中的DataTable.Merge之后:

Print after Merge in MergeAll

经过一些修改以加入MergeAll中的行:

Print after some modifications

更新

由于这个问题出现在其中一个注释中,如果两个表之间的唯一关系是表中DataRow的索引,并且您希望根据索引合并两个表:

public static DataTable MergeTablesByIndex(DataTable t1, DataTable t2)
{
    if (t1 == null || t2 == null) throw new ArgumentNullException("t1 or t2", "Both tables must not be null");

DataTable t3 = t1.Clone();  // first add columns from table1
foreach (DataColumn col in t2.Columns)
{
    string newColumnName = col.ColumnName;
    int colNum = 1;
    while (t3.Columns.Contains(newColumnName))
    {
        newColumnName = string.Format("{0}_{1}", col.ColumnName, ++colNum);
    }
    t3.Columns.Add(newColumnName, col.DataType);
}
var mergedRows = t1.AsEnumerable().Zip(t2.AsEnumerable(),
    (r1, r2) => r1.ItemArray.Concat(r2.ItemArray).ToArray());
foreach (object[] rowFields in mergedRows)
    t3.Rows.Add(rowFields);

   return t3;
}

样品:

var dt1 = new DataTable();
dt1.Columns.Add("ID", typeof(int));
dt1.Columns.Add("Name", typeof(string));
dt1.Rows.Add(1, "Jon");
var dt2 = new DataTable();
dt2.Columns.Add("Country", typeof(string));
dt2.Rows.Add("US");

var dtMerged = MergeTablesByIndex(dt1, dt2);

结果表包含三列ID,名称,国家和一行:1 Jon US&#34;

来源:Combining n DataTables into a Single DataTable 最后访问:2016年8月4日

答案 1 :(得分:0)

首先,您可以过滤右列以分隔数据数据

DataTable  filterDatatable1= new DataTable();
DataTable  filterDatatable2= new DataTable();

DataTable  filterDatatable1= OriginaDatatable1.DefaultView.ToTable(false, "ColumnName1", "ColimnName2");
DataTable  filterDatatable1= OriginaDatatable1.DefaultView.ToTable(false, "ColumnName1", "ColimnName2", "ColimnName3");

然后你可以使用合并功能

DataTable dtAll = new DataTable();

dtAll.Merge(filterDatatable1);
dtAll.Merge(filterDatatable2);