2011-08-02 80 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++; 
} 

哇...这是真的,真的,真的很丑陋....