VB.NETのFor Each文のサンプルです。
目次
For Each文 | For Each文 |
配列の値を取得する | |
リストの値を取得する | |
Exit | For Each文でExitを使用する |
continue | For Each文でcontinueを使用する |
null | For Each文で使用する変数がnullの場合 |
For Each文
For Each ( 変数1 in 配列やリスト等の変数2 ){ 繰り返される箇所(変数1を使用する) } |
- 配列やリストの値を順番に取り出します。
- カウントする変数を使わずにループして配列やリスト等の全ての要素にアクセスします。
- 以下は、MicrosoftのFor Each文のリンクです。
https://docs.microsoft.com/ja-jp/dotnet/visual-basic/language-reference/statements/for-each-next-statement
配列の値を取得する
Module Module1
Sub Main()
Dim a() As String = {"赤", "黄", "青"} '配列
For Each b As String In a
Console.WriteLine(b) '赤 黄 青が出力される
Next
End Sub
End Module
配列の値を取得するサンプルです。
3行目は、配列です。
5~7行目は、For Each文で配列の値を取得しています。
リストの値を取得する
リストの値を取得するサンプルです。
Module Module1
Sub Main()
Dim a As New List(Of String)(New String() {"赤", "黄", "青"})
For Each b As String In a
Console.WriteLine(b) '赤 黄 青が出力される
Next
End Sub
End Module
3行目は、リストに値をセットしています。
5~7行目は、For Each文でリストの値を取得しています。
For Each文でExitを使用する
Exitを使用するサンプルです。
Module Module1
Sub Main()
Dim a() As String = {"赤", "黄", "青"} '配列
For Each b As String In a
If b = "黄" Then
Exit For
End If
Console.WriteLine(b) '赤が出力される
Next
End Sub
End Module
7行目は、ExitでFor Each文のループから抜けます。
結果「赤」のみ出力されます。
For Each文でcontinueを使用する
continueを使用するサンプルです。
Module Module1
Sub Main()
Dim a() As String = {"赤", "黄", "青"} '配列
For Each b As String In a
If b = "黄" Then
Continue For
End If
Console.WriteLine(b) '赤 青が出力される
Next
End Sub
End Module
7行目は、continueでFor Each文の先頭に戻ります。
結果「赤」と「青」が出力されます。
For Each文で使用する変数がnullの場合
For Each文で使用する変数がnullの場合のサンプルです。
Module Module1
Sub Main()
Dim a() As String = Nothing
For Each b As String In a
Console.WriteLine(b) '
Next
End Sub
End Module
3行目の変数はnullです。
For Each文で、System.NullReferenceExceptionの例外が発生するので注意が必要です。
関連の記事
VB.NET For文のサンプル(Exit/Continue)
VB.NET While文のサンプル(Exit/Continue)
VB.NET Do...Loop文のサンプル(Exit/Continue)