從 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);
   }
}

更新於:21-6-2020

727 閱讀

啟動你的 事業

透過完成課程獲得認證

開始
廣告
© . All rights reserved.