Quoting by dataset

While looping through the dataset that the piece of code should use, should I go to 2 foreach or one 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 source to share


3 answers


Second.

foreach (DataRow dr in ds.Tables["TableName"].Rows)

      



Simply because it is easier to read. Adding the index variable "i" just adds complexity. You must be sure to get all the [bounds check] lines. foreach

does what he says.

+1


a source


Operator is operator- foreach

friendly for

when you don't really need a counter / line number ...

The instructions for

introduce a variable i

that you absolutely don't need. (... in your example code)



So, I'll vote for the second ...

+1


a source


The second, for everyone, is more readable, I think. But this is a matter of taste and preference. Choose the one you prefer and the most comfortable one.

One is that two pieces of code don't do the same thing. Did you forget to list the columns in the first one?

0


a source







All Articles