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...
}
Author by
user1080533
Updated on July 18, 2020Comments
-
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 over 12 yearsDamn Lester, now I look like a noob.
-
user1080533 over 12 yearsoh, just one thing...should there not be .Skip(0)?
-
Nuffin over 12 yearsNo, it shouldn't, since
Skip
takes the number of items to ignore. -
user1080533 over 12 yearsOh, didn't know that. Thanks again.
-
Jay Riggs over 12 yearsWhat am I missing - I don't see a Skip method in DataTable.Rows.
-
Adi Lester over 12 years@JayRiggs I just noticed
DataTable.Rows
returns a non-genericIEnumerable
, so in order to use LINQ, a call toCast()
is required. I've updated my answer accordingly. -
Orkun Ozen over 12 yearsalso you should be careful cos I think the "first" row depends on the sorting definition of your datatable.
-
user1080533 over 12 yearsin the end decided not to go with LINQ, so I used your answer. Thank you all for responses.
-
Alan almost 6 yearsAlthough 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 about 5 yearsI've been doing this for years and never even noticed the Skip() method. Don't even feel bad. :)