如何删除数据表中的多个行?

时间:2022-03-13 04:38:21

How can I delete specific DataRows within a loop of a DataTable rows which meet a custom condition -lets say the rows having an index of even number-? (Without using LINQ)

如何在满足自定义条件的DataTable行的循环中删除特定的DataRows ?(没有使用LINQ)

Thanks

谢谢

10 个解决方案

#1


50  

It depends on what you mean by 'delete'.

这取决于你所说的“删除”是什么意思。

If you mean mark them as deleted, just call the Delete() method on each row as you visit it in your loop. You then need to call AcceptChanges() on the data table to finalize the delete - presumably after you update your database (if one is involved).

如果您的意思是将它们标记为已删除,只需在循环中访问每一行时调用Delete()方法。然后,您需要在数据表上调用AcceptChanges()以完成删除操作——可能是在更新数据库之后(如果涉及数据库的话)。

foreach( DataRow row in someTable.Rows )
{
    if( /* your condition here */ )
        row.Delete();
}
someTable.AcceptChanges();

If you mean remove it from the DataTable, then you need to do so in two passes:

如果您的意思是要从DataTable中删除它,那么您需要在两次遍历中这样做:

List<DataRow> rowsToDelete = new List<DataRow>();
foreach( DataRow row in someTable.Rows )
{
    if( /* your condition here */ )
    {
        rowsToDelete.Add( row );
    }
}

foreach( DataRow row in rowsToDelete )
{
    someTable.Rows.Remove( row );
}

It's worth pointing out that you can always use the first method to remove rows - since marking rows as Deleted and then accepting changes will automatically remove them from the table. But, sometimes it is more clear and efficient to simply remove the DataRow objects from the Rows collection.

值得指出的是,您总是可以使用第一个方法来删除行——因为将行标记为已删除,然后接受更改将自动从表中删除它们。但是,有时候简单地从行集合中删除DataRow对象会更清晰、更有效。

#2


8  

Try something like this example

试试这个例子

DataTable table = new DataTable();
table.Columns.Add("Foo",typeof(int));
for (int i = 0; i < 10; i++)
    table.Rows.Add(i);

for (int i = table.Rows.Count -1; i >=0; i--)
{
    // sample removes all even foos
    if ((int)table.Rows[i]["Foo"] % 2 == 0)
        table.Rows.RemoveAt(i);
}

#3


4  

The other way is

另一种方法是

    DataRow[] DrArrCheck = DataTableName.Select("ID > 0");
    foreach(DataRow DrCheck in DrArrCheck)
    {
        DataTableName.Rows.Remove(DrCheck);
    }

#4


4  

If you want a shorter solution than those proposed above, try looping over the list of results, and using a lambda like sub(x) to remove each of those rows.

如果您想要一个比上面建议的更短的解决方案,请尝试循环遍历结果列表,并使用像sub(x)这样的lambda来删除这些行。

dt.Select("Column1 > 0").ToList.ForEach(Sub(x) dt.Rows.Remove(x))

#5


1  

 public static void DeleteRowsFromDataTable(DataTable dataTable, string columnName, string columnValue)
        {
            IEnumerable<DataRow> dataRows = (from t in dataTable.AsEnumerable()
                                             where t.Field<string>(columnName) == columnValue
                                             select t);
            foreach (DataRow row in dataRows)
                dataTable.Rows.Remove(row);
        }

#6


1  

To delete multiple rows (for instance 50,000 out of 100,000) it is much quicker to copy the database than to do either datatable.Rows.Remove(row) or row.Delete(). For instance:

要删除多行(例如,10万中有50,000行),复制数据库要比使用datatable.Rows.Remove(row)或row.Delete()要快得多。例如:

DataRow[] rowsToKeep = datatable.Select("ID > 50000");
DataTable tempDataTable= rowsToKeep.CopyToDataTable;
dataTable.Clear();
dataTable.Merge(tempDataTable);
tempDataTable.Dispose();

#7


0  

try iterating over the result of Select(). This is pretty similar to other answers, but I find it the most direct

尝试遍历Select()的结果。这和其他答案很相似,但我发现它是最直接的

DataRow[] r = table.Select();
for (int i = 0; i < r.Length; i++)
{
    if (i % 2 == 0)
        r[i].Delete();
}

#8


0  

I always used LBushkin's "two-phase" approach and I finally decided it was worth it to write a function for it:

我总是使用LBushkin的“两阶段”方法,我最终决定为它编写一个函数:

    public delegate bool DataRowComparer(DataRow dr);

    public static void RemoveDataRows(DataTable table, DataRowComparer drc)
    {
        List<DataRow> RowsToRemove = new List<DataRow>();
        foreach (DataRow dr in table.Rows)
            if (drc(dr))
                RowsToRemove.Add(dr);
        foreach (DataRow dr in RowsToRemove)
            table.Rows.Remove(dr);
    }

And now I can delete rows with one line of code (for example):

现在我可以用一行代码删除行(例如):

RemoveDataRows(dt, row => row["StringVal"].ToString() == "B" && (Int16)(row["NumberVal"]) >= 4);

In case this helps anyone...

如果这能帮助任何人…

(And any ways to further abbreviate are appreciated.)

(如有任何进一步简化的方法,我们将不胜感激。)

#9


-1  

This is how I did it when I ran into this issue.

这就是我遇到这个问题时的做法。

Dim index As Integer = 0
Dim count As Integer = resultsDT.Rows.Count - 1
For i As Integer = 0 To count
    If resultsDT.Rows(index).Item("something") = "something" Then                               
        resultsDT.Rows(index).Delete()
        resultsDT.AcceptChanges()
        index = index - 1
    End If
    index = index + 1
    i = i + 1
Next

#10


-2  

try this

试试这个

foreach(DataRow oRow in YourDataTable.Rows)
{
  if ("Check You Condition")
   {
      YourDataTable.Rows.Remove(oRow);
   }
}

#1


50  

It depends on what you mean by 'delete'.

这取决于你所说的“删除”是什么意思。

If you mean mark them as deleted, just call the Delete() method on each row as you visit it in your loop. You then need to call AcceptChanges() on the data table to finalize the delete - presumably after you update your database (if one is involved).

如果您的意思是将它们标记为已删除,只需在循环中访问每一行时调用Delete()方法。然后,您需要在数据表上调用AcceptChanges()以完成删除操作——可能是在更新数据库之后(如果涉及数据库的话)。

foreach( DataRow row in someTable.Rows )
{
    if( /* your condition here */ )
        row.Delete();
}
someTable.AcceptChanges();

If you mean remove it from the DataTable, then you need to do so in two passes:

如果您的意思是要从DataTable中删除它,那么您需要在两次遍历中这样做:

List<DataRow> rowsToDelete = new List<DataRow>();
foreach( DataRow row in someTable.Rows )
{
    if( /* your condition here */ )
    {
        rowsToDelete.Add( row );
    }
}

foreach( DataRow row in rowsToDelete )
{
    someTable.Rows.Remove( row );
}

It's worth pointing out that you can always use the first method to remove rows - since marking rows as Deleted and then accepting changes will automatically remove them from the table. But, sometimes it is more clear and efficient to simply remove the DataRow objects from the Rows collection.

值得指出的是,您总是可以使用第一个方法来删除行——因为将行标记为已删除,然后接受更改将自动从表中删除它们。但是,有时候简单地从行集合中删除DataRow对象会更清晰、更有效。

#2


8  

Try something like this example

试试这个例子

DataTable table = new DataTable();
table.Columns.Add("Foo",typeof(int));
for (int i = 0; i < 10; i++)
    table.Rows.Add(i);

for (int i = table.Rows.Count -1; i >=0; i--)
{
    // sample removes all even foos
    if ((int)table.Rows[i]["Foo"] % 2 == 0)
        table.Rows.RemoveAt(i);
}

#3


4  

The other way is

另一种方法是

    DataRow[] DrArrCheck = DataTableName.Select("ID > 0");
    foreach(DataRow DrCheck in DrArrCheck)
    {
        DataTableName.Rows.Remove(DrCheck);
    }

#4


4  

If you want a shorter solution than those proposed above, try looping over the list of results, and using a lambda like sub(x) to remove each of those rows.

如果您想要一个比上面建议的更短的解决方案,请尝试循环遍历结果列表,并使用像sub(x)这样的lambda来删除这些行。

dt.Select("Column1 > 0").ToList.ForEach(Sub(x) dt.Rows.Remove(x))

#5


1  

 public static void DeleteRowsFromDataTable(DataTable dataTable, string columnName, string columnValue)
        {
            IEnumerable<DataRow> dataRows = (from t in dataTable.AsEnumerable()
                                             where t.Field<string>(columnName) == columnValue
                                             select t);
            foreach (DataRow row in dataRows)
                dataTable.Rows.Remove(row);
        }

#6


1  

To delete multiple rows (for instance 50,000 out of 100,000) it is much quicker to copy the database than to do either datatable.Rows.Remove(row) or row.Delete(). For instance:

要删除多行(例如,10万中有50,000行),复制数据库要比使用datatable.Rows.Remove(row)或row.Delete()要快得多。例如:

DataRow[] rowsToKeep = datatable.Select("ID > 50000");
DataTable tempDataTable= rowsToKeep.CopyToDataTable;
dataTable.Clear();
dataTable.Merge(tempDataTable);
tempDataTable.Dispose();

#7


0  

try iterating over the result of Select(). This is pretty similar to other answers, but I find it the most direct

尝试遍历Select()的结果。这和其他答案很相似,但我发现它是最直接的

DataRow[] r = table.Select();
for (int i = 0; i < r.Length; i++)
{
    if (i % 2 == 0)
        r[i].Delete();
}

#8


0  

I always used LBushkin's "two-phase" approach and I finally decided it was worth it to write a function for it:

我总是使用LBushkin的“两阶段”方法,我最终决定为它编写一个函数:

    public delegate bool DataRowComparer(DataRow dr);

    public static void RemoveDataRows(DataTable table, DataRowComparer drc)
    {
        List<DataRow> RowsToRemove = new List<DataRow>();
        foreach (DataRow dr in table.Rows)
            if (drc(dr))
                RowsToRemove.Add(dr);
        foreach (DataRow dr in RowsToRemove)
            table.Rows.Remove(dr);
    }

And now I can delete rows with one line of code (for example):

现在我可以用一行代码删除行(例如):

RemoveDataRows(dt, row => row["StringVal"].ToString() == "B" && (Int16)(row["NumberVal"]) >= 4);

In case this helps anyone...

如果这能帮助任何人…

(And any ways to further abbreviate are appreciated.)

(如有任何进一步简化的方法,我们将不胜感激。)

#9


-1  

This is how I did it when I ran into this issue.

这就是我遇到这个问题时的做法。

Dim index As Integer = 0
Dim count As Integer = resultsDT.Rows.Count - 1
For i As Integer = 0 To count
    If resultsDT.Rows(index).Item("something") = "something" Then                               
        resultsDT.Rows(index).Delete()
        resultsDT.AcceptChanges()
        index = index - 1
    End If
    index = index + 1
    i = i + 1
Next

#10


-2  

try this

试试这个

foreach(DataRow oRow in YourDataTable.Rows)
{
  if ("Check You Condition")
   {
      YourDataTable.Rows.Remove(oRow);
   }
}