Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C#

การใช้ foreach ลูปกับอาร์เรย์ใน C#

ภาพรวม

foreach ใช้วนลูปอ่านสมาชิกอาร์เรย์ตามลำดับ ไม่ต้องจัดการดัชนีเอง ยังมีเมธอดสแตติก Array.Exists สำหรับตรวจสอบเงื่อนไข

ตัวอย่างที่ 1: วนลูปอาร์เรย์สตริงและใช้ Array.Exists

using System;

public class Demo
{
    public static void Main()
    {
        string[] products = new string[] { "Electronics", "Accessories", "Clothing", "Toys", "Clothing", "Furniture" };

        Console.WriteLine("Products list...");
        foreach (string s in products)
        {
            Console.WriteLine(s);
        }

        Console.WriteLine("Is the products Accessories in the array? = {0}", Array.Exists(products, ele => ele == "Accessories"));
        Console.WriteLine("Is the products Stationery in the array? = {0}", Array.Exists(products, ele => ele == "Stationery"));
        Console.WriteLine("\nOne or more products begin with the letter 'C'? = {0}", Array.Exists(products, ele => ele.StartsWith("C")));
        Console.WriteLine("One or more planets begin with 'D'? = {0}", Array.Exists(products, ele => ele.StartsWith("D")));
        Console.WriteLine("One or more products begin with the letter 'T'? = {0}", Array.Exists(products, ele => ele.StartsWith("T")));
        Console.WriteLine("One or more planets begin with 'E'? = {0}", Array.Exists(products, ele => ele.StartsWith("E")));
        Console.WriteLine("Is the array having fixed size? = " + products.IsFixedSize);
    }
}

ผลลัพธ์

Products list...
Electronics
Accessories
Clothing
Toys
Clothing
Furniture
Is the products Accessories in the array? = True
Is the products Stationery in the array? = False
One or more products begin with the letter 'C'? = True
One or more planets begin with 'D'? = False
One or more products begin with the letter 'T'? = True
One or more planets begin with 'E'? = True
Is the array having fixed size? = True

ตัวอย่างที่ 2: เปรียบเทียบอาร์เรย์สองตัว

using System;

public class Demo
{
    public static void Main()
    {
        String[] strArr1 = new String[3] { "John", "Jacob", "Tim" };
        String[] strArr2 = new String[3] { "Tom", "Brad", "Bradley" };

        Console.WriteLine("First String array...");
        foreach (string val in strArr1)
        {
            Console.WriteLine(val);
        }

        Console.WriteLine("Second String array...");
        foreach (string val in strArr2)
        {
            Console.WriteLine(val);
        }

        Console.WriteLine("Are both the array objects equal? = " + strArr1.Equals(strArr2));
    }
}

ผลลัพธ์

First String array...
John
Jacob
Tim
Second String array...
Tom
Brad
Bradley
Are both the array objects equal? = False

สรุป

  • foreach อ่านอย่างเดียว ไม่สามารถแก้ไขสมาชิกได้
  • Array.Exists ใช้ delegate/predicate ตรวจสอบเงื่อนไข
  • Equals ของอาร์เรย์เปรียบเทียบ reference ไม่ใช่เนื้อหา