在 C# 中查詢陣列中最後一個元素的索引


要查詢陣列中最後一個元素的索引,程式碼如下 −

示例

 即時演示

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));
      Console.WriteLine("Index of the last element = "+products.GetUpperBound(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
Index of the last element = 3

示例

現在我們來看看另一個示例 −

 即時演示

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));
      Console.WriteLine("Index of the last element = "+products.GetUpperBound(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
Index of the last element = -1

更新於: 10-Dec-2019

203 次瀏覽

開啟 職業生涯

完成課程以獲得認證

開始學習
廣告
© . All rights reserved.