DataTable, How to conditionally delete rows

前端 未结 4 925
时光取名叫无心
时光取名叫无心 2020-11-30 00:05

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 it

相关标签:
4条回答
  • 2020-11-30 00:17

    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();
    }
    
    0 讨论(0)
  • 2020-11-30 00:19

    Extension method based on Linq

    public static void DeleteRows(this DataTable dt, Func<DataRow, bool> predicate)
    {
        foreach (var row in dt.Rows.Cast<DataRow>().Where(predicate).ToList())
            row.Delete();
    }
    

    Then use:

    DataTable dt = GetSomeData();
    dt.DeleteRows(r => r.Field<double>("Amount") > 123.12 && r.Field<string>("ABC") == "XYZ");
    
    0 讨论(0)
  • 2020-11-30 00:42

    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());
    
    0 讨论(0)
  • 2020-11-30 00:42

    I don't have a windows box handy to try this but I think you can use a DataView and do something like so:

    DataView view = new DataView(ds.Tables["MyTable"]);
    view.RowFilter = "MyValue = 42"; // MyValue here is a column name
    
    // Delete these rows.
    foreach (DataRowView row in view)
    {
      row.Delete();
    }
    

    I haven't tested this, though. You might give it a try.

    0 讨论(0)
提交回复
热议问题