【问题标题】:Insert rows between datasets在数据集之间插入行
【发布时间】:2011-10-18 00:26:45
【问题描述】:

关于问题Modify rows added into dataset,如果我需要在数据集 1 行之间的某处包含数据集 2 行,我应该怎么做?

比如说;

数据集 1

第 1 行
第 2 行
第 3 行
第 4 行

数据集 2

A 行
B 行
C 行

因此,应该是这样的

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

【问题讨论】:

  • 表中的行是无序的。尝试考虑基于排序的解决方案(在 DataView 中)
  • 如果我完全诚实的话;这个问题可以通过改进您的数据库查询来解决。
  • 没有这样的查询。我正在使用数据表行列。
  • 确定将表 2 中的第 x 行插入表 1 的位置的标准是什么?下面的答案是正确的,所有需要添加的是确定在哪里插入行的逻辑。

标签: c# .net asp.net visual-studio dataset


【解决方案1】:

好的,根据 Peyman 回答中的 cmets,这是一种蛮力方法,基于以下假设:

如果表 1 中的给定行在“A”列中有“Y”,则在表 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++;
}

哇……真的,真的,真的很丑……

【讨论】:

    【解决方案2】:

    您可以使用 InsertAt 方法

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

    【讨论】:

    • 我试过了。它抛出一个错误,提到“这一行已经属于另一个表”
    • @Xor power: 你应该创建新的 Row 实例,然后通过 InsertAt 添加它
    • 另外,我将在哪里插入数据集 2 行的位置并不固定。它完全基于数据集 1 的条件
    • 我可以从数据集 1 中获取行位置吗?
    • 我无法找到 dataset-1 行的索引。这是必需的,以便我可以找到在哪里插入 dataset2 的行。类似于 InsertAt 参数中的位置
    【解决方案3】:

    首先数据表有行,数据集保存数据表。 要将行插入特定索引,您可以使用 InsertAt 方法。

    myDataTable.Rows.InsertAt(myNewRow, indexToInsertTo);
    

    【讨论】:

    • 你的答案和之前给出的有什么区别?请不要重复相同的答案。
    • @Karan 不同的是时间,当我发布我的答案时,我看到 Peyman 也发布了它 - 我太慢了,就是这样。只是想在单击“发布您的答案”之前检查(通过启动 VS)我对该方法是否正确。
    • 好吧,我以为你只是复制了相同的答案,所以它没有用,我只是投了反对票,抱歉造成误解。
    猜你喜欢
    • 2022-12-05
    • 2021-10-14
    • 1970-01-01
    • 2012-07-18
    • 1970-01-01
    • 2016-12-13
    • 1970-01-01
    • 1970-01-01
    • 2018-12-22
    相关资源
    最近更新 更多