Why can't I do foreach (var Item in DataTable.Rows)?
Rows
effectively returns IEnumerable
(DataRowCollection
), so the compiler can only pick object
as the type for var
. Use Rows.Cast<DataRow>
if you want to use var
.
Cast
is defined on Enumerable, so you have to include System.Linq.
Brian is absolutely right about the reason for this, but there's a simpler way of avoiding it: use DataTableExtensions.AsEnumerable():
foreach (var row in DataTable.AsEnumerable())
{
...
}