Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DataTable, How to conditionally delete rows

I'm engaged in a C# learning process and it is going well so far. I however just now hit my first "say what?" moment.

The DataTable offers random row access to its Rows collection, not only through typical collections behavior, but also through DataTable.Select. However I cannot seem to be able to tie this ability to DataRow.Delete. So far this is what it seems I need to do in order to conditionally delete one or more rows from a table.

int max = someDataTable.Rows.Count - 1; for(int i = max; i >= 0; --i) {     if((int)someDataTable.Rows[i].ItemArray[0] == someValue)     {         someDataTable.Rows[i].BeginEdit();         someDataTable.Rows[i].Delete();     }     else         break; } someDataTable.AcceptChanges(); 

But I'm not happy with this code. Neither I'm convinced. I must be missing something. Am I really forced to hit the Rows collection sequentially if I need to delete one or more rows conditionally?

(don't mind the inverted for. I'm deleting from the end of the datatable. So it's ok)

like image 200
Alexandre Bell Avatar asked Oct 19 '09 23:10

Alexandre Bell


People also ask

How do you delete a specific row from a table in Javascript?

The deleteRow() method removes the row at the specified index from a table.

How do I delete a row in a DataSet?

When using a DataSet or DataTable in conjunction with a DataAdapter and a relational data source, use the Delete method of the DataRow to remove the row. The Delete method marks the row as Deleted in the DataSet or DataTable but does not remove it.

How do you delete multiple rows in R?

Use -c() with the row id you wanted to delete, Using this we can delete multiple rows at a time from the R data frame. Here row index numbers are specified inside vector c().


2 Answers

You could query the dataset and then loop the selected rows to set them as delete.

var rows = dt.Select("col1 > 5"); foreach (var row in rows)     row.Delete(); 

... and you could also create some extension methods to make it easier ...

myTable.Delete("col1 > 5");  public static DataTable Delete(this DataTable table, string filter) {     table.Select(filter).Delete();     return table; } public static void Delete(this IEnumerable<DataRow> rows) {     foreach (var row in rows)         row.Delete(); } 
like image 160
Matthew Whited Avatar answered Sep 22 '22 16:09

Matthew Whited


Here's a one-liner using LINQ and avoiding any run-time evaluation of select strings:

someDataTable.Rows.Cast<DataRow>().Where(     r => r.ItemArray[0] == someValue).ToList().ForEach(r => r.Delete()); 
like image 39
Alain Avatar answered Sep 20 '22 16:09

Alain