DataTable - foreach Row, EXCEPT FIRST ONE

◇◆丶佛笑我妖孽 提交于 2019-12-04 18:57:54

问题


I am using a DataTable for some calculations in my app. I need to do the iterate trough all the rows except the first one. Is it possible?

Something like:

DataTable dt;

foreach (DataRow r in dt.Rows /*EXCEPT THE FIRST ONE*/)
{
    //do something...
}

回答1:


Ok you got your answers but in case you donT want to use linq. Check the index of the row in the table:

            foreach (DataRow row in m_dtMatrix.Rows)
            {
                if (m_dtMatrix.Rows.IndexOf(row) != 0)
                {
                    ...
                }
            }



回答2:


LINQ is your friend:

DataTable dt;
foreach (DataRow r in dt.Rows.Cast<DataRow>().Skip(1))
{
    //do something...
}

The call to Cast() is required here since DataTable.Rows implements the non-generic IEnumerable, and linq's extension methods are only available for IEnumerable<T>

You also have another option:

DataTable dt;
foreach (DataRow r in dt.AsEnumerable().Skip(1))
{
    //do something...
}



回答3:


Here's a quick and dirty

DataTable dt;

bool isFirst = true;

foreach (DataRow r in dt.Rows /*EXCEPT THE FIRST ONE*/)
{
    if( isFirst ) {
        isFirst = false;
        continue;
    }
    //do something...
}


来源:https://stackoverflow.com/questions/8852863/datatable-foreach-row-except-first-one

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