For Each

ADO DOT NET

Centurion
Joined
Dec 20, 2006
Messages
160
Visual Basic:
Dim SStr() As String = something...

                For MyLoop As Integer = 0 To SStr.Length - 1

                Next
Hi,
You see that I use a loop to go through all arrays of SStr.
Is it possible to convert this code so I can use For Each instead?
I don't know how to use For Each for this one.
Thanks:)
 
This should get you going in the right direction.

Visual Basic:
Dim SStr() as String = {"Val1","Val2","Val3"}
For Each s as String in SStr
    Console.WriteLine(s)
Next

Output should be:
Val1
Val2
Val3
 
The problem here is that we can't see what you are doing inside the loop. Generally, a For Each loop can be substituted for the loop you've written in the original post, but if you need the index of the item you are examining, a For Each won't cut it.

Just to show the difference:
Code:
[Color=Blue]Dim [/Color]SStr() [Color=Blue]as String [/Color]= {"Val1","Val2","Val3"}
[Color=Blue]For [/Color]index [Color=Blue]As Integer [/Color]= 0 [Color=Blue]to[/Color] SStr.Length - 1
    Console.WriteLine(index.ToString() & ": " & SStr(index))
[Color=Blue]Next [/Color]
results in:
Code:
0: Val1
1: Val2
2: Val3
 
The original code is looping over each character (or position, really) in the string. A foreach isn't *guaranteed* to loop in order so I'm not sure that's what you'd want. I think the equivalent foreach wouldn't be very nice, but here's something to try if you want:
1. Convert the string into an array of char.
2. Foreach char in the array of char

For "foreach" to work, you've got to have something you can enumerate over - generally some type of array or list. A string doesn't have that natively - you'll have to convert to an array of some kind.

If you have an array of strings, or a string with a delimiter, then you should be able to "foreach string in stringarray". Your sample didn't seem to show that though...

Let us know more of what's going on and we may be able to help more.

-ner
 
For Each and strings

Nerseus, you are incorrect on both counts, I'm afraid. The original code is looping over an array of strings rather than the characters in a single string. Even so, you can still use For Each over the characters in a string without needing to use ToCharArray:

Visual Basic:
For Each c As Char In myString
    Console.Write(c)
Next

You are correct in that For Each isn't guaranteed to iterate over the items in order, but I'd be absolutely amazed if it didn't when iterating over an ordered list or a string.

Good luck :cool:
 
Back
Top