长沙震烨科技有限公司 专注研发高校招生考试系统

分别从table1和table2中检索出不行同的记录然后加到newTable中

2016/11/25 10:05:58 人评论 次浏览 分类:C#学习中心

DataTable table1 = new DataTable();
      table1.Columns.Add("Id", typeof(int));
      table1.Columns.Add("Name", typeof(String));
      table1.Rows.Add(1, "John");
      table1.Rows.Add(2, "Tom");
      table1.Rows.Add(5, "Helen");

      DataTable table2 = new DataTable();
      table2.Columns.Add("Id", typeof(int));
      table2.Columns.Add("Name", typeof(String));
      table2.Rows.Add(2, "Tom");
      table2.Rows.Add(4, "Peter");
      table2.Rows.Add(5, "Helen");

      DataTable newTable = new DataTable();
      newTable.Columns.Add("Id", typeof(int));
      newTable.Columns.Add("Name", typeof(String));
      foreach (DataRow row in table1.Rows)
      {
        DataRow[] rows = table2.Select("Id=" + row[0].ToString() + " AND Name='" + row[1].ToString() + "'");
        if (rows.Length == 0)
        {
          newTable.Rows.Add(int.Parse(row[0].ToString()),row[1].ToString());
        }
      }

      foreach (DataRow row in table2.Rows)
      {
        DataRow[] rows = table1.Select("Id=" + row[0].ToString() + " AND Name='" + row[1].ToString() + "'");
        if (rows.Length == 0)
        {
          newTable.Rows.Add(int.Parse(row[0].ToString()), row[1].ToString());
        }
      }

附件下载