6

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 ...

1 Answer 1

7

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);
}
Sign up to request clarification or add additional context in comments.

5 Comments

is it not possible with the select method?
i dont know a specifyDate before
See my edit. You can calculate specifyDate before executing query
now the second thing is, that you get only one max, but i have several ID's and each ID should after the select statement only exists one time tihe the newest date
all fine but he dont get the specifyDate (changes Date to Time) my definition looks like: time.ColumnName = "Time"; time.DataType = Type.GetType("System.DateTime"); data.Columns.Add(time);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.