How to remove rows from a DataTable in C # with a filter?

I have a DataTable with some rows, one of them is ID (row) and System.DateTime. other lines are not important now.

now I want to delete all rows with the same identifier that has an older date-date as the newest.

Is it possible?

here is an example

  • ID: 123 Date: 12/24/2010 ...
  • ID: 123 Date: 12/23/2010 ...
  • ID: 123 Date: 12/22/2010 ...

after that I only want:

  • ID: 123 Date: 12/24/2010 ...
+6
source share
1 answer

Try the following

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); } 
+7
source

Source: https://habr.com/ru/post/888227/


All Articles