Updating an arraylist using a For Each Loop
Hi All,
I can do this with a for loop, but I was just curious if an arraylist can be updated using a for each loop. ie
Code:
For Each arrItem As String In myArrayList
arrItem = "My Stuff"
Next
If I loop through the arraylist again the values remain unchanged. Am I missing something here?
Thanks,
Strick
Re: Updating an arraylist using a For Each Loop
basically arrItem in your For-Each statement is a variable which if changed does not change the original value.
You would use a For/Next to index elements
Code:
Dim Values As New ArrayList
Values.Add("First")
Values.Add("Second")
Dim Temp As String = ""
For row As Integer = 0 To Values.Count - 1
Temp = Values(row).ToString
Values(row) = Temp & " !!!"
Next
For Each item In Values
Console.WriteLine(item)
Next
MSDN http://msdn.microsoft.com/en-us/library/5ebk1751.aspx
Re: Updating an arraylist using a For Each Loop
Unless you are working with VS2003 or earlier, you shouldn't be using ArrayLists at all. That alone might be causing the trouble, because an ArrayList is a list of objects. It would be entirely possible for that arraylist to be holding pretty nearly anything, including holding only one item in many different places, though that doesn't seem to be quite the situation here.
EDIT: The replacement for ArrayList for use with 2005 or later, is List(of T). In your case, if the list holds strings, that would mean a List(of String). Try it, you'll like it.
Re: Updating an arraylist using a For Each Loop
Thanks guys. I'll try these out when I get to work.
Strick
Re: Updating an arraylist using a For Each Loop
It may still not work... since strings are immutable, your variable that holds the string in the foreach, is a copy of the string from the list. So what you end up changing is a copy of the string... not the list itself. But admitedly I don't use List(of String) very often... I'm usually dealing with a list of objects, which are reference based...
-tg