เรามาดูตัวอย่างการรวบรวมรายการ
เราได้กำหนดองค์ประกอบ -
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);
}
}