如何比较两个表,然后使用LINQ将不匹配的数据插入到新表中

时间:2014-02-27 00:49:53

标签: c# sql linq

    private void SampleSolution(DataTable dt1, DataTable dt2)
    {
        var matched = from Customers in dt1.AsEnumerable()
                  join Orders in dt2.AsEnumerable() on Customers.Field<string>("FirstName") equals Orders.Field<string>("FirstName")
                     where Customers.Field<string>("FirstName") == Orders.Field<string>("FirstName") || Customers.Field<string>("LastName") == Orders.Field<string>("LastName") 
                  select Customers;
        var missing = from Customers in dt1.AsEnumerable()
                      where !matched.Contains(Customers)
                      select Customers;

        //This should give the rows which do not have a match.

    }

然后我用了

    private void button1_Click(object sender, EventArgs e)
    {
        SqlConnection Connection = new SqlConnection("Data Source=sql2;" +
                                   "user id=UserConn;password=""=;" +
                                   "Initial Catalog=AITest; ");

        // Assumes that connection is a valid SqlConnection object.
        string queryString1 =
          "SELECT * FROM dbo.Customers"; 
        SqlDataAdapter custAdapter = new SqlDataAdapter(queryString1, Connection);

        string queryString2 =
          "SELECT * FROM dbo.Orders";
        SqlDataAdapter ordAdapter = new SqlDataAdapter(queryString2, Connection);


        DataSet customersOrders = new DataSet();
        custAdapter.Fill(customersOrders, "Customers");
        ordAdapter.Fill(customersOrders, "Orders");

        DataTable customerTable = customersOrders.Tables["Customers"];
        DataTable OrderTable = customersOrders.Tables["Orders"];

        SampleSolution(customerTable, OrderTable);

现在我需要将不匹配的数据插入到新表中。怎么样???任何人都可以帮助我

0 个答案:

没有答案