0% found this document useful (0 votes)
35 views4 pages

Foreach Loop

Uploaded by

seviwos198
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
35 views4 pages

Foreach Loop

Uploaded by

seviwos198
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

In VB.

NET, a `For` loop can be used to iterate over collections by using an index
to access each item in the collection. Unlike `For Each`, which automatically
iterates through each item, a `For` loop gives you more control over the index
and can be useful when you need to access elements by their position.

Here's the syntax for using a `For` loop to iterate over a collection:

```vb

For index As Integer = 0 To [Link] - 1

' Access each item using collection(index)

Next

```

### Example with a List

Suppose you have a list of strings and want to print each item using a `For`
loop:

```vb

Dim fruits As New List(Of String) From {"Apple", "Banana", "Cherry"}

For i As Integer = 0 To [Link] - 1

[Link](fruits(i))

Next

```

This will output:


```

Apple

Banana

Cherry

```

### Example with an Array

If you're working with an array, you can use a similar approach. Here’s an
example:

```vb

Dim numbers() As Integer = {10, 20, 30, 40, 50}

For i As Integer = 0 To [Link] - 1

[Link](numbers(i))

Next

```

This will output:

```

10

20

30
40

50

```

### Example with a Dictionary (Accessing Keys by Index)

For a `Dictionary`, you cannot directly access items by index, as dictionaries


are not indexed collections. However, you can get the keys or values as a list
and use the `For` loop to access elements by position:

```vb

Dim studentGrades As New Dictionary(Of String, Integer) From {

{"Alice", 90},

{"Bob", 85},

{"Charlie", 92}

Dim keys As List(Of String) = [Link]()

For i As Integer = 0 To [Link] - 1

Dim key As String = keys(i)

[Link]($"{key}: {studentGrades(key)}")

Next

```

This will output:


```

Alice: 90

Bob: 85

Charlie: 92

```

In [Link], a `For` loop can provide more control over iteration, especially
when you need to access items by their index or perform custom logic based on
the position in the collection.

You might also like