Why can't I do foreach (var Item in DataTable.

2019-01-06 20:46发布

Is there a reason why I can't do the following:

foreach (var Item in DataTable.Rows) {

rather than having to do

foreach (DataRow Item in DataTable.Rows) {

I would have thought this was possible, like it is on other datatypes. For example:

foreach (var Employee in Staff) { // string[] Staff etc...

When I try the first foreach loop, I get the the error CS0021: Cannot apply indexing with [] to an expression of type 'object'.

Why can't the compiler figure out that .Rows returns a collections of DataRows?

2条回答
我想做一个坏孩纸
2楼-- · 2019-01-06 21:03

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.

查看更多
一夜七次
3楼-- · 2019-01-06 21:15

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())
{
    ...
}
查看更多
登录 后发表回答