Search code examples
c#objectdatatable

error CS0021: Cannot apply indexing with [] to an expression of type 'object'


My code:

foreach(var row in dt_test.Rows)
{
    if (DateTime.ParseExact(row["TestDate"].ToString(),"dd.MM.yyyy",System.Globalization.CultureInfo.InvariantCulture) > DateTime.ParseExact("01.11.2019","dd.MM.yyyy",System.Globalization.CultureInfo.InvariantCulture))
    {
        dt_test.Rows.Remove(row);
    }
}
dt_test.AcceptChanges();

Error:

error CS0021: Cannot apply indexing with [] to an expression of type 'object'

How i can fix it?

I tried to redo for linq query, but nothing worked out for me.


Solution

  • The reason for the error is that you use var in the foreach and not DataRow. If you'd use the latter, the foreach could automatically cast the object to DataRow. DataRowCollection, which is returned from DataTable.Rows, is old and does not implement IEnumerable<DataRow> but just the non-generic ICollection. That's why the foreach gets an object.

    foreach(DataRow row in dt_test.Rows)
    {
       // now you can use the methods of DataRow like the indexer
    }
    

    Apart from that you cannot remove rows from a table in a foreach while you are enumerating it. You will get an exception "Collection was modified; enumeration operation might not execute". But you could fill a remove-list first:

    List<DataRow> removeList = new();
    foreach(DataRow row in dt_test.Rows)
    {
       If(condition)
       {
           removeList.Add(row);
       }
    }
    removeList.ForEach(dt_test.Rows.Remove);