Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

howto delete rows from DataTable in C# with a filter?

i have a DataTable with some rows, one of it is a ID (a string) and a System.DateTime. the other rows are not important now.

now i want to delete all the rows with the same ID that have an older DateTime as the newest.

is this possible?

here an example

  • ID:123 Date:24.12.2010 ...
  • ID:123 Date:23.12.2010 ...
  • ID:123 Date:22.12.2010 ...

after this i only want:

  • ID:123 Date:24.12.2010 ...
like image 707
hansgiller Avatar asked May 16 '11 14:05

hansgiller


People also ask

How do I delete multiple records in a DataTable?

For adding delete control you can either add a delete button with each record or add checkboxes and a single delete button. In this tutorial, I show how you add multiple checkboxes and delete selected records on a single click in DataTables using jQuery AJAX.

Can we update DataTable in C#?

use SetModified() method to update data table value.


1 Answers

Try next

public void DeleteOldById(DataTable table, int id)
{
      var rows = table.Rows.Cast<DataRow>().Where(x => (int)x["ID"] == id);
      DateTime specifyDate = rows.Max(x => (DateTime)x["Date"])

      rows.Where(x =>(DateTime)x["Date"] < specifyDate).ToList().
           ForEach(x => x.Delete());
}


public void DeleteAllOldRows(DataTable table)
{
     var ids = table.Rows.Cast<DataRow>().Select(x => (int)x["ID"]).Distinct();
     foreach(int id in ids)
        DeleteOldById(table,id);
}
like image 59
Stecya Avatar answered Oct 25 '22 05:10

Stecya