10

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...
}
Adi Lester
  • 24,731
  • 12
  • 95
  • 110
user1080533
  • 865
  • 2
  • 21
  • 35

3 Answers3

32

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...
}
Adi Lester
  • 24,731
  • 12
  • 95
  • 110
16

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)
                {
                    ...
                }
            }
Orkun
  • 6,998
  • 8
  • 56
  • 103
  • 1
    also you should be careful cos I think the "first" row depends on the sorting definition of your datatable. – Orkun Jan 13 '12 at 15:39
  • in the end decided not to go with LINQ, so I used your answer. Thank you all for responses. – user1080533 Jan 14 '12 at 12:49
  • Although this is the accepted answer (and a valid one), checking for every row not being the first isn't ideal, @Adi 's skipping of the first row is a more concise, clean way of doing it. – Alan Jun 21 '18 at 08:09
2

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...
}
Matthew
  • 24,703
  • 9
  • 76
  • 110