foreach statement, atau sering disebut foreach in merupakan pengulangan sekelompok pernyataan untuk setiap elemen dalam array yang intinya tidak begitu berdeda dengan for statement.
//C#
foreach (int element in fibarray)
[statement]
[break]
[continue]
'VB
For Each element [As datatype] In group
[statement]
[Exit For]
[Continue For]
Next [element]
Agar tidak bingung langsung saja kita mencontohkannya. Buat 1 Project dengan nama cs_04foreach (untuk C#) dan vb_04foreach (untuk VB), kemudian masukan 1 object listbox dan 3 object button seperti gambar 15.1 dibawah ini:
Gambar 15.1
Atur properties button sebagai berikut:
| Object | Properties | Value |
| button1 | (Name) | btnForeach |
| Teks | Foreach | |
| button2 | (Name) | btnStop |
| Teks | Stop | |
| button3 | (Name) | btnCon |
| Teks | Continue |
Foreach
Sebagai contoh kita memiliki kelompok array dengan data 0, 1, 5, 6, 8, 9, 12, 15.
Klik 2x button foreach kemudian ketikan code beribut:
//C#
private void btnForeach_Click(object sender, EventArgs e)
{
ListBox1.Items.Clear();
int[] kelompok = new int[] { 0, 1, 5, 6, 8, 9, 12, 15 };
foreach (int i in kelompok)
{
ListBox1.Items.Add(i);
}
}
'VB
Private Sub btnForeach_Click(sender As Object, e As EventArgs) Handles btnForeach.Click
ListBox1.Items.Clear
Dim kelompok() as Integer = {0, 1, 5, 6, 8, 9, 12, 15}
For Each i As Integer In kelompok
ListBox1.Items.Add(i)
Next
End Sub
Gambar 15.2
Stop
Sekarang kita coba menghentikan pada saat array berada pada angka 9.
Klik 2x button stop kemudian ketikan code beribut:
//C#
private void btnStop_Click(object sender, EventArgs e)
{
ListBox1.Items.Clear();
int[] kelompok = new int[] { 0, 1, 5, 6, 8, 9, 12, 15 };
foreach (int i in kelompok)
{
ListBox1.Items.Add(i);
if (i == 9)
{
break;
}
}
}
'VB
Private Sub btnStop_Click(sender As Object, e As EventArgs) Handles btnStop.Click
ListBox1.Items.Clear
Dim kelompok() as Integer = {0, 1, 5, 6, 8, 9, 12, 15}
For Each i As Integer In kelompok
ListBox1.Items.Add(i)
If i = 9 Then
Exit For
End If
Next
End Sub
Gambar 15.3
Continue
Sekarang kita mencoba untuk lewati pada saat array diangka 5-9 kemudian pada saat array berada pada angka 12 kita hentikan.
Klik 2x button continue kemudian ketikan code beribut: //C#
private void btnCon_Click(object sender, EventArgs e)
{
ListBox1.Items.Clear();
int[] kelompok = new int[] { 0, 1, 5, 6, 8, 9, 12, 15 };
foreach (int i in kelompok)
{
if(i >= 5 & i <= 9)
{
continue;
}
ListBox1.Items.Add(i);
if (i == 12)
{
break;
}
}
}
'VB
Private Sub btnCon_Click(sender As Object, e As EventArgs) Handles btnCon.Click
ListBox1.Items.Clear
Dim kelompok() as Integer = {0, 1, 5, 6, 8, 9, 12, 15}
For Each i As Integer In kelompok
If i >= 5 And i <= 9 Then
Continue For
End If
ListBox1.Items.Add(i)
If i = 12 Then
Exit For
End If
Next
End Sub
Gambar 15.4
Cukup Sampai disini contoh dari foreach statement, next kita masuk kepembahasan Do Statement.
Password: csvb2015.blogspot.co.id





Tidak ada komentar :
Posting Komentar