Tutorial :What is wrong with this loop



Question:

I'm using a loop condition to check if there is null value in the columns, then remove it.

-Original author

[STart:]      For i As Integer = counter To dt1.Columns.Count - 1        For x As Integer = 0 To dt1.Rows.Count - 1          if some condition then              something = true          else                  something = false              counter = counter + 1                  Goto [Start]          end if        Next          If something = true          dt1.Columns.Remove(dt1.Columns(i))          i -= 1        End If      Next    End If  

Sometimes it runs correctly and sometimes even though when i becomes greater than (dt.columns.count - 1), it still executes the for loop and throws an error that there is no column with that index. I must be missing something here but I'm not able to debug the issue.

Do you guys find anything wrong with this code?


Solution:1

The statement dt1.Columns.Count is evaluated at the very beginning of the for loop. It does not get re-evaluated each time the loop runs.

So when you remove a column in the body of the loop it causes the end condition of the loop to go wrong.


Solution:2

I'm guessing that the i-loop only evaluates the stopping value once.


Solution:3

Its a bad idea to alter the object on which you are looping. This might be having an effect in some cases. I would copy your datatable - loop on the first table and alter the second.

Also, have you seen the Select method on datatable? It might make this search for null values easier then embedded loops (loop on the columns and call select)

Dim DRs AS DataRow() = dt1.Select(dt1.Columns(i).ColumnName " IS NULL")  If DRs.Count > 0 Then      '' // do something  End If  


Solution:4

Since you are deleting in your outer loop, don't rely upon the reevalution of dt1.Columns.Count

Further, try counting down instead of up (because if you delete a column in your count down, it won't affect what the next valid index is)

Something like this for your outer loop:

warning: I'm a c# developer, my syntax for the vb for loop might be off read: I want to loop down from the highest column number down to column 0

'' // leave no question as to how often count will be evaluated.  '' //  we will ensure it happens only once:  Dim colmns as int = dt1.Columns.Count - 1  for i as integer = columns to 0 step -1   '' // your logic goes here    '' // DON'T manualy modify the value of i -- it will always be right.  Next  

This works better in reverse. Think about it like this: say I have 4 columns, and I am on #3. If # 3 is non-null, I will leave it alone, and my next column is #2 If #3 is null, I will delete it, but my next columns is still #2, and I'm still finished when I get to zero.


Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »