DataTable - foreach Row, EXCEPT FIRST ONE

user1080533 picture user1080533 · Jan 13, 2012 · Viewed 33.3k times · Source

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...
}

Answer

Adi Lester picture Adi Lester · Jan 13, 2012

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...
}