Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

arrays

csv

vb.net

I am making a program that automates the seperation of a csv file. We read the csv in through and then assign the "line" using a split command to an array. After that we go through each "cell" in the array and put an = in front because this causes leading zeros not to be lost. Here's the code.

        arLine = line.Split(replace)

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

arLine is the array and replace is the delimiter, in this case a pipe not that it matters.'

When it goes through, the arLine is correct but the values in each cell are not changing, any thoughts? newer to VB.net and need direction

like image 801
Coomanperson Avatar asked Jun 13 '12 15:06

Coomanperson


People also ask

Can you modify array in foreach?

Note that foreach does not modify the internal array pointer, which is used by functions such as current() and key(). It is possible to customize object iteration. In order to be able to directly modify array elements within the loop precede $value with &. In that case the value will be assigned by reference.

How do you resize an array in VB net?

The ReDim statement is used to declare a dynamic array. To resize an array, we have used a Preserve keyword that preserve the existing item in the array. The array_name represents the name of the array to be re-dimensioned. A subscript represents the new dimension of the array.

What is foreach in VB net?

In the VB.NET, For Each loop is used to iterate block of statements in an array or collection objects. Using For Each loop, we can easily work with collection objects such as lists, arrays, etc., to execute each element of an array or in a collection.


2 Answers

Try with this.

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 are looping using For Each and trying to modify the value returned by the iterator, but this creates a new string for your cell var, so you are not referencing the original array. Instead, using a traditional for - loop, you could update directly the values in the arLine array

like image 170
Steve Avatar answered Nov 14 '22 20:11

Steve


Strings in .NET are immutable. When you modify a string, you actually create a brand-new string.

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

Use a for loop rather than foreach so that you have a handy index into the collection.

like image 34
Eric J. Avatar answered Nov 14 '22 21:11

Eric J.