從 C# 集合中檢索元素


我們來看一個列表集合的例子。

我們已經設定了以下元素 -

List<int> list = new List<int>();
list.Add(20);
list.Add(40);
list.Add(60);
list.Add(80);

現在讓我們假設我們需要從列表中檢索第一個元素。為此,請將索引設定為以下格式 -

int a = list[0];

以下是一個演示如何從列表集合中檢索元素的示例 -

示例

using System;
using System.Collections.Generic;

class Demo {

   static void Main(String[] args) {
      List<int> list = new List<int>();
      list.Add(20);
      list.Add(40);
      list.Add(60);
      list.Add(80);

      foreach (int val in list) {
         Console.WriteLine(val);
      }

      int a = list[0];
      Console.WriteLine("First element: "+a);
   }
}

更新於:2020 年 6 月 21 日

727 次瀏覽

開啟你的職業生涯

完成課程並獲得認證

開始
廣告
© . All rights reserved.