獲取或設定在 C# 中 List 的指定索引處的元素


獲取或設定列表中特定索引處的元素,程式碼如下 -

示例

 動態演示

using System;
using System.Collections.Generic;
public class Demo {
   public static void Main(String[] args) {
      List<String> list = new List<String>();
      list.Add("100");
      list.Add("200");
      list.Add("300");
      list.Add("400");
      list.Add("500");
      list.Add("600");
      list.Add("700");
      list.Add("800");
      list.Add("900");
      list.Add("1000");
      Console.WriteLine("Element at index 0 = " + list[0]);
      Console.WriteLine("Element at index 1 = " + list[1]);
      Console.WriteLine("Element at index 2 = " + list[2]);
      Console.WriteLine("Element at index 3 = " + list[3]);
      Console.WriteLine("Element at index 4 = " + list[4]);
      Console.WriteLine("Element at index 5 = " + list[5]);
      Console.WriteLine("Element at index 6 = " + list[6]);
      Console.WriteLine("Element at index 7 = " + list[7]);
   }
}

輸出

這會產生以下輸出 -

Element at index 0 = 100
Element at index 1 = 200
Element at index 2 = 300
Element at index 3 = 400
Element at index 4 = 500
Element at index 5 = 600
Element at index 6 = 700
Element at index 7 = 800

示例

讓我們看另一個示例 -

 動態演示

using System;
using System.Collections.Generic;
public class Demo {
   public static void Main(String[] args) {
      List<String> list = new List<String>();
      list.Add("100");
      list.Add("200");
      list.Add("300");
      list.Add("400");
      list.Add("500");
      list.Add("600");
      list.Add("700");
      list.Add("800");
      list.Add("900");
      list.Add("1000");
      Console.WriteLine("Element at index 0 = " + list[0]);
      Console.WriteLine("Element at index 1 = " + list[1]);
      Console.WriteLine("Element at index 2 = " + list[2]);
      Console.WriteLine("Element at index 3 = " + list[3]);
      Console.WriteLine("Element at index 4 = " + list[4]);
      Console.WriteLine("Element at index 5 = " + list[5]);
      Console.WriteLine("Element at index 6 = " + list[6]);
      Console.WriteLine("Element at index 7 = " + list[7]);
      list[3] = "450";
      Console.WriteLine("Element at index 3 [UPDATED] = " + list[3]);
   }
}

輸出

這會產生以下輸出 -

Element at index 0 = 100
Element at index 1 = 200
Element at index 2 = 300
Element at index 3 = 400
Element at index 4 = 500
Element at index 5 = 600
Element at index 6 = 700
Element at index 7 = 800
Element at index 3 [UPDATED] = 450

更新時間:2019 年 12 月 10 日

108 次閱讀

開啟你的 事業

透過完成課程以獲得認證

開始學習
廣告