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

Key-based I/O Collections ใน C# คืออะไร

Key-based I/O Collections ใน C# คือ SortedList<TKey, TValue> - คอลเลกชัน Key-Value ที่จัดเรียงตาม Key อัตโนมัติ เข้าถึงได้ทั้ง Key และ Index

การเพิ่มข้อมูล

SortedList<string, string> s = new SortedList<string, string>();
s.Add("Sub1", "Physics");
s.Add("Sub2", "Chemistry");
s.Add("Sub3", "Biology");
s.Add("Sub4", "Java");

โค้ดตัวอย่างเต็ม

using System;
using System.Collections.Generic;

namespace Demo
{
    class Program
    {
        static void Main(string[] args)
        {
            SortedList<string, string> s = new SortedList<string, string>();
            s.Add("Sub1", "Economics");
            s.Add("Sub2", "Accountancy");
            s.Add("Sub3", "Business Studies");
            s.Add("Sub4", "English");
            
            Console.WriteLine("Capacity = " + s.Capacity);
            
            // ดึง Keys และแสดง
            foreach (string k in s.Keys)
            {
                Console.WriteLine(k + ": " + s[k]);
            }
        }
    }
}

ผลลัพธ์

Capacity = 4
Sub1: Economics
Sub2: Accountancy
Sub3: Business Studies
Sub4: English

คุณสมบัติสำคัญ

  • จัดเรียงตาม Key อัตโนมัติ (Sorted by Key)
  • เข้าถึงได้โดย Key: s["Sub1"]
  • เข้าถึงได้โดย Index: s.GetValueAtIndex(0)
  • Key ต้อง Unique (ไม่ซ้ำ)
  • Generic Version: SortedList<TKey, TValue> (แนะนำ)
  • Non-generic: SortedList (Legacy)

SortedList vs Dictionary

คุณสมบัติSortedListDictionary
เรียงลำดับตาม Key (Auto)ไม่เรียง (Unordered)
เข้าถึงโดย Indexได้ (O(1))ไม่ได้
Performance (Insert)O(n)O(1)
Memoryน้อยกว่ามากกว่า