查询两个DataTable以查找重复的行

时间:2012-10-25 16:10:29

标签: c# asp.net sql-server linq

我有一个excel表,我使用sqlbulkcopy上传到sqlserver表,我在数据库表上应用了一个索引,以便忽略重复的条目,但我也想显示在网格视图中被忽略的重复条目。 / p>

  protected void Button1_Click(object sender, EventArgs e)
{
    string strFileType = System.IO.Path.GetExtension(FileUpload1.FileName).ToString().ToLower();
    string strFileName = FileUpload1.PostedFile.FileName.ToString();

    FileUpload1.SaveAs(Server.MapPath("~/Import/" + strFileName + strFileType));
    string strNewPath = Server.MapPath("~/Import/" + strFileName + strFileType);






        string excelConnectionString = String.Format(@"Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source="+strNewPath +"; Extended Properties=Excel 8.0;");

    //string excelConnectionString = String.Format(@"Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source=C:\\myFolder\\Book1.xls;" + "Extended Properties=Excel 8.0;"); 


        // Create Connection to Excel Workbook
        using (OleDbConnection connection = new OleDbConnection(excelConnectionString))
        {
            connection.Open();
            OleDbCommand command = new OleDbCommand("Select ID,Data FROM [Sheet1$]", connection);
            OleDbCommand command1 = new OleDbCommand("select count(*) from [Sheet1$]",connection);

            //Sql Server Table DataTable
            DataTable dt4=new DataTable();
            SqlCommand cmd4 = new SqlCommand("select id,data from ExcelTable", con);
            try 
                { 
                    SqlDataAdapter da4 = new SqlDataAdapter(cmd4); 
                    da4.Fill(dt4);//sql table datatable
                 }
                catch { }


            //excelsheet datatable
            DataTable oltlb = new DataTable();
          OleDbCommand olcmd = new OleDbCommand("select id,data from [Sheet1$]", connection);
          try
          {
              OleDbDataAdapter olda = new OleDbDataAdapter(olcmd);
              olda.Fill(oltlb); //excel table datatable
          }
          catch { }

    var matched = (from table1 in dt4.AsEnumerable()
                         join table2 in oltlb.AsEnumerable() on
                       table1.Field<int>("ID") equals table2.Field<int>("ID")
                         where table1.Field<string>("Data") == table2.Field<string>("Data")
                         select table1);
          DataTable dthi5 = new DataTable();
          dthi5 = matched.CopyToDataTable();

          GridView1.DataSource = dthi5;
          GridView1.DataBind();
            GridView1.DataSource = matched.ToList();

错误: 指定演员表无效。 table1.Field(“ID”)等于table2.Field(“ID”)

1 个答案:

答案 0 :(得分:0)

看来,其中一个表中的ID字段不是int。

不是我们中的一个或两个猜测,而是尝试检查两个表(oltlb和dt4)中第一列的数据类型,以查看哪个具有非整数数据类型。事实上它可能都是。

这就是:即使字符串的值是数字文字,也不能将字符串转换为int。您必须使用Int32.ParseConvert.ToInt32进行转换。因此,如果您的某个表具有ID列的字符串类型,您可以这样表达:

table1.Field<int>("ID") equals Convert.ToInt32(table2.Field<string>("ID"))

如果两个表都有字符串ID字段,您可以这样表达:

table1.Field<string>("ID") equals table2.Field<string>("ID")