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

杀马特。学长 韩版系。学妹 提交于 2019-11-26 09:54:10

问题


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?


回答1:


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.




回答2:


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())
{
    ...
}


来源:https://stackoverflow.com/questions/2325777/why-cant-i-do-foreach-var-item-in-datatable-rows

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!