迴圈讓相同邏輯重複執行,陣列高效管理同類資料集合。掌握 VB.NET 在 Razor 中的迴圈語法與陣列操作,處理動態資料呈現。
已知迭代次數時使用 For...Next 迴圈,支援正向遞增與反向遞減:
<html>
<body>
@For i = 10 To 21
@<p>Line #@i</p>
Next i
</body>
</html>
語法:For counter = start To end [Step step],Step 預設為 1,可設定負值實現倒數。
處理陣列、集合、IEnumerable 物件時,For Each...Next 提供最簡潔的遍歷語法:
<html>
<body>
<ul>
@For Each x In Request.ServerVariables
@<li>@x</li>
Next x
</ul>
</body>
</html>
自動處理列舉器建立與釋放,程式碼更安全簡潔。適用於任何實作 IEnumerable 介面的物件。
Do While...Loop 結構在條件為 True 時持續執行,適合無法預知迭代次數的場景:
<html>
<body>
@Code
Dim i = 0
Do While i < 5
i += 1
@<p>Line #@i</p>
Loop
End Code
</body>
</html>
+= 運算子每次迴圈遞增計數器。需確保迴圈內修改條件變數,避免無限迴圈。另提供 Do Until...Loop (條件為 False 時執行) 與 Do...Loop While (至少執行一次) 變體。
陣列以單一變數儲存多個同類型值,透過索引 (0-based) 存取元素:
@Code
Dim members As String() = {"Jani", "Hege", "Kai", "Jim"}
i = Array.IndexOf(members, "Kai") + 1
len = members.Length
x = members(2 - 1)
End Code
<html>
<body>
<h3>Members</h3>
@For Each person In members
@<p>@person</p>
Next person
<p>The number of names in Members are @len</p>
<p>The person at position 2 is @x</p>
<p>Kai is now in position @i</p>
</body>
</html>
關鍵陣列操作:Length 取得元素數、IndexOf 搜尋元素索引、For Each 遍歷。VB.NET 陣列索引以 0 起始,但範例中 members(2-1) 示範第 2 個元素 (索引 1)。
@Code
Dim products = GetProductsFromDatabase()
Dim totalPrice = 0
End Code
<table>
@For Each product In products
totalPrice += product.Price
@<tr>
<td>@product.Name</td>
<td>@product.Price.ToString("C")</td>
</tr>
Next
@<tr><td>Total</td><td>@totalPrice.ToString("C")</td></tr>
</table>