2011-08-02 34 views
0

參考問題Modify rows added into dataset,如果需要在數據集1行之間包含數據集2行,應該怎麼做?在數據集之間插入行

舉例說;

數據集1

行1
行2
第3行
第4行

數據集2

A行
B排
C行

因此,這應該是這樣

行1
A行
行2
第3行
B排
第4行
C行

+0

表中的行是無序的。試着想一個基於Sorting(在DataView中)如果我完全誠實的 –

+1

的解決方案;這個問題可以通過改進你的數據庫查詢來解決。 – f0x

+0

沒有這樣的查詢。我正在使用數據錶行列。 –

回答

2

可以使用InsertAt methos

var row = dataSet2.Tables[0].NewRow(); 
// Copy rowA to row 
dt.Rows.InsertAt(row, position); 
+0

我試過了。它會拋出一個錯誤提到「這行已經屬於另一個表」 –

+0

@Xor power:你應該創建新的Row實例,然後通過InsertAt添加它 – Peyman

+0

另外,位置不固定,我將插入數據集2的位置行。,它完全基於數據集1條件 –

1

首先,數據表具有行和數據集包含數據表。 要將行插入到特定索引,可以使用InsertAt方法。

myDataTable.Rows.InsertAt(myNewRow, indexToInsertTo); 
+0

你的答案和之前的答案有什麼區別?請不要重複相同的答案。 –

+2

@Karan不同之處在於TIME,當我發佈我的答案時,我看到Peyman也發佈了它 - 我太慢了。只是想檢查(通過開始VS),如果我在點擊「發佈您的答案」之前正確地使用了該方法。 – Reniuz

+0

好吧,我以爲你剛剛複製它相同的答案,所以它沒有用,這就是我只是投了下來抱歉的誤解。 –

0

確定的基礎上,由Peyman的答案的評論,這裏是一個強制的方法,基於以下假設:

如果在表1中給定的行具有「Y」列「 A「,在表1中的當前行之後插入表2中的一行。每當滿足該條件時,從表2中取出下一個未使用的行。我會先說這是醜陋的,並且容易出現很多問題,並且可能有更好的方法來做到這一點(LINQ?),也許是解釋Xor試圖完成什麼(即,它背後的概念/規則/邏輯)可能會導致更好或替代解決方案。

這裏所說:

int tbl1Index = 0; 
int tbl1Rows = dataset1.Tables[0].Rows.Count; 
int tbl2Index = 0; 
int tbl2Rows = dataset2.Tables[0].Rows.Count; 

DataRow row; 

// Do this loop until either tbl1 has been gone through completely or table 2 has been gone 
// through completely, whichever comes first. 
while (tbl1Index < tbl1Rows && tbl2Index < tbl2Rows) 
{ 
    if (dataset1.Tables[0].Rows[tbl1Index]["A"].ToString() == "Y") 
    { 
     // Copy the next available row from table 2 
     row = dataset2.Tables[0].Rows[tbl2Index]; 
     // Insert this row after the current row in table 1 
     dataset1.Tables[0].Rows.InsertAt(row, tbl1Index + 1); 

     // Increment the tbl1Index. We increment it here because we added a row, even 
     // though we'll increment tbl1Index again before the next iteration of the while loop 
     tbl1Index++; 
     // Since we just inserted a row, we need to increase the count of rows in table 1 to 
     // avoid premature exit of the while loop 
     tbl1Rows++; 
     // Increment tbl2Index so the next time a match occurs, the next row will be grabbed. 
     tbl2Index++; 
    } 

    // Increment tbl1Index. If there was a match above, we'll still need to increment to 
    // account for the new row. 
    tbl1Index++; 
} 

哇...這是真的,真的,真的很醜陋....