簡體   English   中英

將第一個數據表的行與第二個數據表的列進行比較,並使用匹配的列構建第三個數據表

[英]Compare Row of 1st Datatable with Column of 2nd Datatable and build 3rd datatable with matched columns

http://www.codeproject.com/Questions/733071/Compare-Row-of-1st-Datatable-with-Column-of-2nd-Da (理解問題)這些是我的兩個數據表(Visual C#)

table1

|Par Name.........| Par #|.......Units |.......LSL  |   USL | -----SKIP |
Diffusion.........908513100.......-..........  0  -----99.9  -----1 
Program...........908514100.......-.........  99.5--- 999    -----





table2
starttime   | Product      | Device   | Diffusion       | Program | 
11/7/2013    SAF5100EL       163       -0.145712003      -0.146583006                                 
11/7/2013    SAF5100EL        84       -0.137499005      -0.137592003
11/7/2013    SAF5100EL        44       -0.142690003      -0.143250003  
11/7/2013    SAF5100EL       164       -0.139434993      -0.140459001
11/7/2013    SAF5100EL        34       -0.147183999      -0.148519993

輸出應該看起來像

table3 
  |Diffusion|       | Program |
 -0.145712003      -0.146583006
 -0.137499005      -0.137592003
 -0.142690003      -0.143250003
 -0.139434993      -0.140459001
 -0.147183999      -0.148519993

在這里,必須從datatable2中獲取與table1的行名匹配的table2中的列(例如,此處的擴散和程序),並且必須創建新的DataTable3並使用列的排序值(Diffusion和Program)

正如其他人所說,這是直截了當的邏輯,您應該首先自己嘗試。 這也會給您信心。

無論如何,下面的代碼應該可以解決問題。 Tweek,根據您的方便。 還要徹底測試。

//dt1 contains Diffusion etc as rows
//dt2 contains diffusion etc as columns
//dt3 is the required table
DataTable dt3 = new DataTable();
DataRow dr = null;

for (int i = 0; i < dt1.Rows.Count; i++)
{
    string col = dt1.Rows[i]["Par Name"].ToString();
    if (dt2.Columns.Contains(col))
    {
        if (!dt3.Columns.Contains(col))
        {
            dt3.Columns.Add(col, typeof(string));
        }

        if (dt3.Rows.Count == 0)
        {
            for (int j = 0; j < dt2.Rows.Count; j++)
            {
                dr = dt3.NewRow();
                dt3.Rows.Add(dr);
            }
        }

        for (int j = 0; j < dt2.Rows.Count; j++)
        {
            dt3.Rows[j][col] = dt2.Rows[j][col].ToString();
        }
    }
}

希望這可以幫助。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM