Giới thiệu
Duyệt mảng dùng vòng lặp for với chỉ số i từ 0 đến Length - 1. Cách cơ bản nhất, cho phép truy cập chỉ số.
Ví dụ cơ bản
string[] str = { "Videos", "Tutorials", "Tools", "InterviewQA" };
for (int i = 0; i < str.Length; i++)
{
string res = str[i];
Console.WriteLine(res);
}
Ví dụ hoàn chỉnh
using System;
public class Demo
{
public static void Main()
{
string[] str = { "Videos", "Tutorials", "Tools", "InterviewQA" };
Console.WriteLine("String Array...");
for (int i = 0; i < str.Length; i++)
{
string res = str[i];
Console.WriteLine(res);
}
}
}
Kết quả
String Array... Videos Tutorials Tools InterviewQA
Các cách duyệt mảng khác
| Cách | Cú pháp | Ưu điểm | Nhược điểm |
|---|---|---|---|
| for | for(int i=0;i | Có index, hiệu suất cao, cho phép sửa mảng | Verbose |
| foreach | foreach(var s in arr) | Ngắn gọn, an toàn, readable | Không có index, không sửa mảng được |
| for (reverse) | for(int i=arr.Length-1;i>=0;i--) | Duyệt ngược, an toàn khi xóa | |
| LINQ | arr.Select((v,i)=>...) | Functional, chainable | Overhead delegate |
Lưu ý
Lengthlà property O(1), không tính toán mỗi lần.- Không sửa đổi mảng (thêm/xóa) trong foreach -> InvalidOperationException.
- Với mảng lớn, cache
Lengthvào biến cục bộ (micro-optimization).