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

การหาดัชนีของสมาชิกแรกในอาร์เรย์ใน C#

ภาพรวม

เมธอด Array.GetLowerBound(int dimension) คืนดัชนีต่ำสุดของมิติที่ระบุ (0-based) สำหรับอาร์เรย์มิติเดียวจะคืน 0 เสมอ

ตัวอย่างที่ 1: อาร์เรย์สตริง 4 ตัว

using System;

public class Demo
{
    public static void Main()
    {
        string[] products = new string[] { "Andy", "Mark", "Gary", "Andre" };

        Console.WriteLine("One or more name begin with 'A'? = {0}", Array.Exists(products, ele => ele.StartsWith("A")));
        Console.WriteLine("Is the array having fixed size? = " + products.IsFixedSize);
        Console.WriteLine("Is the array read only? = " + products.IsReadOnly);
        Console.WriteLine("Is the array synchronized? = " + products.IsSynchronized);
        Console.WriteLine("Index of the 1st element = " + products.GetLowerBound(0));
    }
}

ผลลัพธ์

One or more name begin with 'A'? = True
Is the array having fixed size? = True
Is the array read only? = False
Is the array synchronized? = False
Index of the 1st element = 0

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

using System;

public class Demo
{
    public static void Main()
    {
        string[] products = new string[] { };

        Console.WriteLine("Is the array having fixed size? = " + products.IsFixedSize);
        Console.WriteLine("Is the array read only? = " + products.IsReadOnly);
        Console.WriteLine("Is the array synchronized? = " + products.IsSynchronized);
        Console.WriteLine("Index of the 1st element = " + products.GetLowerBound(0));
    }
}

ผลลัพธ์

Is the array having fixed size? = True
Is the array read only? = False
Is the array synchronized? = False
Index of the 1st element = 0

สรุป

  • GetLowerBound(0) สำหรับอาร์เรย์ 1 มิติ คืน 0 เสมอ
  • อาร์เรย์ใน C# เป็น zero-based และ fixed-size
  • ใช้ GetUpperBound(0) หาดัชนีสูงสุด (Length - 1)