Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> C#

Duyệt mảng chuỗi với for loop trong C#


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áchCú phápƯu điểmNhược điểm
forfor(int i=0;iCó index, hiệu suất cao, cho phép sửa mảngVerbose
foreachforeach(var s in arr)Ngắn gọn, an toàn, readableKhô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
LINQarr.Select((v,i)=>...)Functional, chainableOverhead delegate

Lưu ý

  • Length là 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 Length vào biến cục bộ (micro-optimization).