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

คลาส SortedList ใน C# คืออะไร

SortedList เป็นคอลเลกชันที่รวม Array และ Hash Table ไว้ด้วยกัน เข้าถึงได้ทั้งโดย Index และ Key ข้อมูลจะถูกจัดเรียงตาม Key อัตโนมัติ

ตัวอย่าง: เพิ่ม Key-Value Pair

using System;
using System.Collections;

namespace Demo
{
    class Program
    {
        static void Main(string[] args)
        {
            SortedList s = new SortedList();
            s.Add("S1", "Maths");
            s.Add("S2", "Science");
            s.Add("S3", "English");
            s.Add("S4", "Economics");
        }
    }
}

ตัวอย่าง: ดึง Keys และแสดงค่า

using System;
using System.Collections;

namespace Demo
{
    class Program
    {
        static void Main(string[] args)
        {
            SortedList sl = new SortedList();
            sl.Add("ST0", "One");
            sl.Add("ST1", "Two");
            sl.Add("ST2", "Three");
            sl.Add("ST3", "Four");
            sl.Add("ST4", "Five");
            sl.Add("ST5", "Six");
            sl.Add("ST6", "Seven");
            
            ICollection keys = sl.Keys;
            foreach (string k in keys)
            {
                Console.WriteLine(k + ": " + sl[k]);
            }
        }
    }
}

ผลลัพธ์

ST0: One
ST1: Two
ST2: Three
ST3: Four
ST4: Five
ST5: Six
ST6: Seven

Generic Version (แนะนำ)

using System.Collections.Generic;

SortedList<string, string> sl = new SortedList<string, string>();
sl.Add("key1", "value1");