Reputation: 5096
While looping through a Dataset which code snippet should I use, should I go for 2 foreach or a single for
snippet1:
for (int i = 0; i < ds.Tables["TableName"].Rows.Count; i++)
{
// My Code
}
snippet2:
foreach (DataRow dr in ds.Tables["TableName"].Rows)
{
foreach (DataColumn dc in ds.Tables["TableName"].Columns)
{
//My Code
}
}
Upvotes: 1
Views: 1834
Reputation: 13692
The foreach
statement is favourable to the for
statement when you don't actually need the counter/row number...
The for
statements introduces the i
variable, for which you have absolutely no need. (...in your sample code)
So I vote for the second one...
Upvotes: 1
Reputation: 36340
The second one, foreach, is more readable I think. But this is a question of taste and preferences. Choose whichever you prefer and is most comfortable with.
One this - the two code snippets don't do the same. Did you forget to enumerate the columns in the first?
Upvotes: 0
Reputation: 19960
The second one.
foreach (DataRow dr in ds.Tables["TableName"].Rows)
Simply because it is easier to read. Adding an index variable "i" just adds complexity. You need to be sure your getting all the rows [bounds check]. foreach
does what it says.
Upvotes: 1