Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C#

Collections (คอลเลกชัน) ใน C#

Collection classes เป็นคลาสเฉพาะสำหรับจัดเก็บและดึงข้อมูล รองรับ stacks, queues, lists, hash tables ส่วนใหญ่ implement interfaces เดียวกัน

คลาสคอลเลกชันหลักใน C#

  • ArrayList - คอลเลกชันลำดับของออบเจ็กต์ ที่เข้าถึงด้วยดัชนีได้
  • Hashtable - ใช้คีย์เข้าถึงสมาชิก
  • SortedList - ใช้คีย์และดัชนีเข้าถึงรายการ
  • BitArray - อาร์เรย์การแทนค่าบाइनารี 0 และ 1
  • Stack - Last-in, first-out (LIFO)
  • Queue - First-in, first-out (FIFO)

ตัวอย่าง ArrayList

using System;
using System.Collections;

namespace Demo {
    class Program {
        static void Main(string[] args) {
            ArrayList al = new ArrayList();
            al.Add(99);
            al.Add(76);
            al.Add(87);
            al.Add(46);
            al.Add(55);
            
            Console.WriteLine("Capacity: {0}", al.Capacity);
            Console.WriteLine("Count: {0}", al.Count);
            Console.Write("Elements: ");
            foreach (int i in al) Console.Write(i + " ");
            Console.WriteLine();
            Console.ReadKey();
        }
    }
}

ผลลัพธ์

Capacity: 8
Count: 5
Elements: 99 76 87 46 55