SQL and Java Learner SQL and Java Learner - 5 months ago 9x
Vb.net Question

What's the easiest and most efficient way to shift values in cells down by one in VB.net?

I used a for loop to shift data down by one in an array:

For x = 0 To (UBound(stringArray) - 1)
stringArray(x) = stringArray(x + 1)


The data consists of strings, contains roughly 10-12 characters. I was wondering, is there a more efficient way to do this, or is using a for loop the best way to accomplish this?


You could use Array.Copy in this way

Dim stringArray = {"1", "2", "3", "4", "5"}
Array.Copy(stringArray, 1, stringArray, 0, stringArray.Length-1)
-- stringArray is: 2,3,4,5,5

but on a so small scale (15 elements) this is hardly a step worth to take.
You could keep your actual code without any perceivable difference.

Or better, use the Skip extension for a lot more readable code:

Dim stringArray = {"1", "2", "3", "4", "5"}
Dim secondArray = stringArray.Skip(1)
-- secondArray is: 2,3,4,5

Consider also that this last example creates a new array with all the original elements less the last one, while your loop or the first example changes the original array leaving the last element still in place. This could be desiderable or not depending on your constraints.