The Pragmatic Programmer

Tulisan iseng kalo ada waktu.
See also: Other Geeks@INDC

VB For Loop and C# For Loop

I have a list of integer that contains four data, let says I use an array list:

            System.Collections.ArrayList arl = new System.Collections.ArrayList();

            arl.Add(1);
            arl.Add(0);
            arl.Add(1);
            arl.Add(1);
 

I want to remove all zeros from the list but I must iterate the list, so I use this algorithm to achieve it:

            for(int i = 0; i < arl.Count; i++)
            {
                if(((int)arlIdea) == 0)
                {
                    arl.RemoveAt(i);
                    i--;
                }
            }

How to do it in VB? Any one knows? 

It seems simple, but remember, nothing as simple as it seems.

Share this post: | | | |

Comments

cahnom said:

Dim arl As New System.Collections.ArrayList()

arl.Add(1)

arl.Add(0)

arl.Add(1)

arl.Add(1)

While arl.Contains(0)

   arl.Remove(0)

End While

# November 5, 2007 3:23 PM

irwansyah said:

No..no...no...only use for loop not other loop

# November 5, 2007 3:39 PM

cahnom said:

Dim arl As New System.Collections.ArrayList()

arl.Add(1)

arl.Add(0)

arl.Add(1)

arl.Add(1)

Dim i As Integer

For i = 0 To arl.Count

   If arl.Contains(0) Then arl.Remove(0) Else Exit For

Next

# November 5, 2007 5:01 PM

Dea said:

How do I achieve the same result using LINQ?

Does anybody know how?

# November 5, 2007 6:00 PM

irwansyah said:

Actually, my point is I want to show that in VB the for loop codition is cached and never evaluated again to get the actual current value that is if you wrote the above code into its VB.Net equivalent like shown below:

for i as integer = 0 to arl.Count - 1

 if ctype(arl(i), integer) = 0 then

    arl.RemoveAt(i)

    i -= 1

 end if

Next

You'll get index out of bound exception. Does any one know why VB.Net behaving like that?

# November 6, 2007 10:35 AM