Changing the value of an array through the foreach VB.net statement

I am making a program that automates the separation of a csv file. We read csv in end-to-end mode and then assign a "string" using the split command for the array. After that, we go through each "cell" in the array and put a = in front, because this leads to the fact that leading zeros are not lost. Here is the code.

arLine = line.Split(replace) For Each cell As String In arLine cell = cell.Replace(",", "") cell = String.Format(cellFormat, cell) Next 

arLine is an array, and replace is a separator, in this case it is not important. ''

When it passes, arLine is correct, but the values ​​in each cell do not change, any thoughts? newer to VB.net and need direction

+4
source share
2 answers

Try it out.

 arLine = line.Split(replace) For x as Integer = 0 To arLine.Lenght - 1 arLine(x) = arLine(x).Replace(",", "") arLine(x) = String.Format(cellFormat, arLine(x)) Next 

You loop using the "For Everyone" parameter and try to change the value returned by the iterator, but this creates a new line for your var variable, so you are not referencing the original array. Instead, using the traditional for-loop, you can directly update the values ​​in the arLine array

+7
source

Strings in .NET: immutable . When you change a line, you create a completely new line.

So, the cell no longer refers to the original element of the array. Instead, try a for loop, not a foreach , and assign the changed value back to arLine(i) .

Use a for foreach , not a foreach , so you have a convenient index in the collection.

+4
source

All Articles