2012-04-25 77 views
0

有一個數據集Ds1和數據集Ds2,DS1有Product_ID,產品信息和ds2有Product_ID,product_type。將一列從一個DataSet添加到其他

對於匹配的product_id,我想將Product_tye列從ds2添加到ds1。

注意:product_id不是DS 1中的主鍵,結果集有許多具有相同product_id的產品。在ds 2中,product_id是唯一的。此外,這些數據來自不同服務器上的兩個不同數據庫,並具有不同的憑據,因此無法使用SQL連接。

我試圖用linq來實現這個目標,但是沒有得到想要的輸出結果,如果我正在開發一些東西,請糾正我。

DataTable dt1 = new DataTable(); 
DataTable dt2 = new DataTable(); 
//After both the datatble has values, using linq to add datatble columsn, 

DataTable result = (from t1 in dt1.AsEnumerable() 
          join t2 in dt2.AsEnumerable() on t1.Field<string>("productID") equals t2.Field<string>("productID") 
          select t1).CopyToDataTable(); 
+0

我獻疑這將取代string去那麼簡單。您必須在table1中創建一個新列,然後遍歷這兩個表的行並檢查id,並根據產品ID將prodict_type添加到table1的確切行。 – 2012-04-25 18:13:51

回答

0

選擇這兩個表

DataTable result = (from t1 in dt1.AsEnumerable() 
         join t2 in dt2.AsEnumerable() on t1.Field<string>("productID") 
            equals t2.Field<string>("productID") 
         select new {t1,t2} 
        ).CopyToDataTable(); 

或選擇選定列

DataTable result = (from t1 in dt1.AsEnumerable() 
         join t2 in dt2.AsEnumerable() on t1.Field<string>("productID") 
             equals t2.Field<string>("productID") 
         select new { 
         productId = t1.productID, 
         col2 = t1.col2,..., 
         productType = t2.pruductType 
        ).CopyToDataTable(); 

注:我認爲的productID類型應該是int類型,以便與詮釋在這種情況下

+0

第二個查詢:需要關閉選定列列表後的花括號。 '選擇新的{....}' – Kaf 2012-04-25 18:40:13

0

我剛剛創建你一個簡單的例子,你必須做的是列名從我的代碼更改,用自己:

 DataTable table1 = new DataTable(); 
     DataTable table2 = new DataTable(); 
     table1.Columns.Add("id", typeof(int)); 
     table1.Columns.Add("name", typeof(string)); 
     table2.Columns.Add("id", typeof(int)); 
     table2.Columns.Add("age", typeof(int)); 

     table1.Rows.Add(1, "mitja"); 
     table1.Rows.Add(2, "sandra"); 
     table1.Rows.Add(3, "nataška"); 

     table2.Rows.Add(1, 31); 
     table2.Rows.Add(3, 24); 
     table2.Rows.Add(4, 46); 

     DataTable targetTable = table1.Clone(); 
     //create new column 
     targetTable.Columns.Add("age"); 

     var results = from t1 in table1.AsEnumerable() 
         join t2 in table2.AsEnumerable() on t1.Field<int>("id") equals t2.Field<int>("id") 
         select new 
         { 
          ID = (int)t1["id"], 
          NAME = (string)t1["name"], 
          AGE = (int)t2["age"] 
         }; 

     foreach (var item in results) 
      targetTable.Rows.Add(item.ID, item.NAME, item.AGE); 

要小心定義的變量類型(INT ,字符串,...)在任何情況下! 希望它有幫助。

+0

非常感謝..工作 – Softwaresucks 2012-04-25 20:41:26

相關問題