DataTable - foreach Row, EXCEPT FIRST ONE

34,911

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

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

Solution 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...
}
Share:
34,911
user1080533
Author by

user1080533

Updated on July 18, 2020

Comments

  • user1080533
    user1080533 almost 4 years

    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...
    }
    
  • Matthew
    Matthew over 12 years
    Damn Lester, now I look like a noob.
  • user1080533
    user1080533 over 12 years
    oh, just one thing...should there not be .Skip(0)?
  • Nuffin
    Nuffin over 12 years
    No, it shouldn't, since Skip takes the number of items to ignore.
  • user1080533
    user1080533 over 12 years
    Oh, didn't know that. Thanks again.
  • Jay Riggs
    Jay Riggs over 12 years
    What am I missing - I don't see a Skip method in DataTable.Rows.
  • Adi Lester
    Adi Lester over 12 years
    @JayRiggs I just noticed DataTable.Rows returns a non-generic IEnumerable, so in order to use LINQ, a call to Cast() is required. I've updated my answer accordingly.
  • Orkun Ozen
    Orkun Ozen over 12 years
    also you should be careful cos I think the "first" row depends on the sorting definition of your datatable.
  • user1080533
    user1080533 over 12 years
    in the end decided not to go with LINQ, so I used your answer. Thank you all for responses.
  • Alan
    Alan almost 6 years
    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.
  • DevOhrion
    DevOhrion about 5 years
    I've been doing this for years and never even noticed the Skip() method. Don't even feel bad. :)