Bỏ qua để đến nội dung

Vòng lặp

Vòng lặp dùng để chạy lại một khối code. foreach phù hợp khi duyệt collection; for phù hợp khi cần index.

Vòng lặpKhi nào dùng
forBiết số lần lặp hoặc cần index
whileLặp khi điều kiện còn đúng
do whileChạy ít nhất 1 lần
foreachDuyệt từng phần tử trong collection
for (int i = 0; i < 5; i++)
{
Console.WriteLine(i);
}
int count = 0;
while (count < 3)
{
Console.WriteLine(count);
count++;
}
int choice;
do
{
choice = 0;
Console.WriteLine("Menu chạy ít nhất một lần");
} while (choice != 0);
var names = new List<string> { "An", "Binh", "Chi" };
foreach (string name in names)
{
Console.WriteLine(name);
}
for (int i = 1; i <= 5; i++)
{
if (i == 3) continue;
if (i == 5) break;
Console.WriteLine(i);
}
var names = new List<string> { "An", "Binh", "Chi" };
for (int i = 0; i < names.Count; i++)
{
Console.WriteLine($"{i}: {names[i]}");
}
for (int i = names.Count - 1; i >= 0; i--)
{
if (names[i].StartsWith("A"))
{
names.RemoveAt(i);
}
}
var scores = new Dictionary<string, int>
{
["An"] = 9,
["Binh"] = 8
};
foreach ((string name, int score) in scores)
{
Console.WriteLine($"{name}: {score}");
}

Dùng khi muốn tạo sequence lười (lazy sequence), không cần build list ngay.

IEnumerable<int> EvenNumbers(int max)
{
for (int i = 0; i <= max; i += 2)
{
yield return i;
}
}
  • Quên tăng biến đếm trong while, gây vòng lặp vô hạn.
  • Xóa phần tử khỏi collection khi đang foreach.
  • Dùng break khi thật ra cần continue.
  • Duyệt List bằng for nhưng dùng i <= list.Count.
  • Gọi LINQ nhiều lần trong loop làm tốn chi phí không cần thiết.

loop, vòng lặp, for, while, do while, foreach, break, continue, yield return, duyệt danh sách, duyệt Dictionary, xóa phần tử khi duyệt