VB.NETのFor Each文のサンプルです。
目次
| サンプル | For Each文 | 
| 配列の値を取得する | |
| リストの値を取得する | |
| 文字列を1文字ずつ取得する | |
| ディクショナリのキーと値を取得する | |
| Exit | ループを抜ける(Exit For) | 
| continue | ループの先頭に戻る(Continue For) | 
For Each文
| For Each ( 変数1 in 配列やリスト等の変数2 ){ 実行される処理(変数1を使用する) } | 
- 配列やリストの全ての要素を順番に取り出します。
- カウントする変数は使用しません。
- 使用する変数がnullの場合System.NullReferenceExceptionの例外が発生します。
- 以下は、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 Module3行目は、配列です。
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 Module3行目は、リストです。
5~7行目は、For Each文でリストの値を取得しています。
文字列を1文字ずつ取得する
Module Module1
	Sub Main()
		Dim str As String = "ABCD"
		For Each s1 As String In str
			Console.WriteLine(s1) 'A B C Dが出力される
		Next
	End Sub
End Module文字列をforeach文でループさせた場合、1文字ずつ取得できます。
ディクショナリのキーと値を取得する
Module Module1
	Sub Main()
		Dim a As New Dictionary(Of String, String)
		a.Add("A", "赤")
		a.Add("B", "黄")
		a.Add("C", "青")
		For Each b In a
			Console.WriteLine(b.Key) 'A B Cと出力される
			Console.WriteLine(b.Value) '赤 黄 青と出力される
		Next
	End Sub
End Module3行目は、ディクショナリです。
9行目はキーを10行目は値を取得しています。
ループを抜ける(Exit For)
Exit Forでループを抜けるサンプルです。
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 Module7行目は、Exit Forでループから抜けます。
結果「赤」のみ出力されます。
ループの先頭に戻る(Continue For)
Continue Forでループの先頭に戻るサンプルです。
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 Module7行目は、Continue Forでループの先頭(5行目)に戻ります。
結果「赤」と「青」が出力されます。
関連の記事
VB.NET For文 処理を繰り返す(Exit/Continue)
VB.NET While文のサンプル(Exit/Continue)
VB.NET Do...Loop文のサンプル(Exit/Continue)
