Search code examples
c#datetimedatasetenumerable

Deleting specific DateTime column rows from a DataTable


I am currently selecting some specific rows from a datatable which contain DateTime column. The idea is to delete these specific rows after collecting them.

EnumerableRowCollection<DateTime?> dates =
    dataSet.Tables[0].AsEnumerable()
    .Select(r => r.Field<DateTime?>(dateColumn))
    .Where((r => r < minDate || r > maxDate));

I am getting the rows in a RowCollection, how do i actually delete these rows from the Dataset/DataTable? Or perhaps a better way to do it.


Solution

  • To delete a row from a datatable you need to perform some operations.

    First find all the rows that match your criteria

    var rowsToDelete = dataSet.Tables[0].AsEnumerable()
                      .Where(r => r.Field<DateTime?>(dateColumn) < minDate ||
                                  r.Field<DateTime?>(dateColumn) > maxDate));
    

    Now start marking each row as deleted.

    foreach(DataRow row in rowsToDelete)
        row.Delete();
    

    Notice that the previous step marks only the rows as deleted, the rows are still in the datatable but they are no more accessible (And trying to use a row with its RowState == DataRowState.Deleted causes an exception)

    Now you could remove these rows from the DataTable calling

    dataSet.Tables[0].AcceptChanges();
    

    Also note that this code doesn't change anything on the database table but only makes changes to the in memory DataTable. If you want to remove the rows from the database table then you need specific ADO.NET code specific for your database - For example in Sql Server you need to call the SqlDataAdapter.Update method for a batch delete or a sequence of single SqlCommand with the appropriate DELETE statement for each of the row to delete.