Getting compiler error while using for each row loop , i am trying to filter an excel sheet and want to display the filtered result



You need to use for each instead of for each row with TypeArgument System.Data.DataRow

You are iterating a DataRow Array not a DataTable.

To make your logic work add values.CopyToDataTable in for each row.


Hi vvaidya,
while using for each it is not showing the result instead it shows

else this error displayed


.CopyToDataTable returns a DataTable object, so you’d need to use:

Foreach System.DataRow item in values.CopyToDataTable().Rows

But it’s redundant.
It’s a matter of understanding your data types.
.Select(filter) returns an Array of DataRow (or DataRow[]). You can iterate it directly with ForEach loop if you set TypeArgument to System.DataRow, since Arrays are IEnumerable.

.CopyToDataTable returns a DataTable object. You can iterate it with ForEachRow loop directly (Foreach row in yourDataTable) or with ForEach loop if you specify the rows collection (Foreach row in yourDataTable.Rows).

Sidenote/personal opinion:
I’d recommend against using ForEachRow in the long run, as it can only accept a DataTable object. If you’ll use ForEach loop, you can use any IEnumerable<T> type - arrays, lists etc. without redoing the activity (so f.e. if you need to add a filter through .Select you don’t need to jump the hoops of .CopyToDataTable - it will work as-is, since both DataRow[] and DataTable.Rows are an IEnumerable<DataRow>).