views:

114

answers:

3

Hi All, 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
            }

        }
+1  A: 

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.

Dead account
Thanks Ian for ur suggestion
Wondering
A: 

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?

Rune Grimstad
+1  A: 

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

Arjan Einbu