Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DataTable - foreach Row, EXCEPT FIRST ONE

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...
}
like image 371
user1080533 Avatar asked Jan 13 '12 15:01

user1080533


People also ask

How to skip first row in foreach loop c#?

It's easiest to use the Skip method in LINQ to Objects for this, to skip a given number of elements: foreach (var value in sequence. Skip(1)) // Skips just one value { ... } Obviously just change 1 for any other value to skip a different number of elements...

How to get first row Data from DataTable?

use Datatable. rows(0) this will give you the first row in the datatable.

What information is shown in the top row of a data table?

A table header row is the top row of a table that acts as a title for the type of information they will find in each column.


2 Answers

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...
}
like image 101
Adi Lester Avatar answered Oct 25 '22 11:10

Adi Lester


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)
                {
                    ...
                }
            }
like image 35
Orkun Ozen Avatar answered Oct 25 '22 09:10

Orkun Ozen