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
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.
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.
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.
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With