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

ดึงค่าทั้งหมดใน SortedList ใน C#

ภาพรวม

SortedList.Values คุณสมบัติคืนค่า ICollection ที่มีค่าทั้งหมดเรียงตามลำดับคีย์ คู่กับ Keys ที่คืนคีย์ทั้งหมด

ตัวอย่างที่ 1: ดึงค่าและคีย์จาก SortedList แบบ int key, string value

using System;
using System.Collections;

public class Demo
{
    public static void Main(String[] args)
    {
        SortedList list = new SortedList();
        list.Add(1, "One");
        list.Add(2, "Two");
        list.Add(3, "Three");
        list.Add(4, "Four");
        list.Add(5, "Five");
        ICollection col1 = list.Values;
        Console.WriteLine("Values...");
        foreach(string s in col1)
            Console.WriteLine(s);
        ICollection col2 = list.Keys;
        Console.WriteLine("Keys...");
        foreach(int s in col2)
            Console.WriteLine(s);
    }
}

ผลลัพธ์

Values...
One
Two
Three
Four
Five
Keys...
1
2
3
4
5

ตัวอย่างที่ 2: ดึงค่าและคีย์จาก SortedList แบบ string key, string value

using System;
using System.Collections;

public class Demo
{
    public static void Main(String[] args)
    {
        SortedList list = new SortedList();
        list.Add("A", "Jacob");
        list.Add("B", "Sam");
        list.Add("C", "Tom");
        list.Add("D", "John");
        list.Add("E", "Tim");
        list.Add("F", "Mark");
        list.Add("G", "Gary");
        list.Add("H", "Nathan");
        list.Add("I", "Shaun");
        list.Add("J", "David");
        ICollection col1 = list.Values;
        Console.WriteLine("Values...");
        foreach(string s in col1)
            Console.WriteLine(s);
        ICollection col2 = list.Keys;
        Console.WriteLine("\nKeys...");
        foreach(string s in col2)
            Console.WriteLine(s);
    }
}

ผลลัพธ์

Values...
Jacob
Sam
Tom
John
Tim
Mark
Gary
Nathan
Shaun
David
Keys...
A
B
C
D
E
F
G
H
I
J

คำอธิบายเพิ่มเติม

  • Values และ Keys คืนค่า ICollection view การเปลี่ยนแปลง SortedList สะท้อนทันที
  • ลำดับของ Values และ Keys ตรงกัน (คีย์ที่ i สอดคล้องกับค่าที่ i)
  • SortedList เรียงตามคีย์ ใช้ binary search O(log n) สำหรับการค้นหา
  • ไม่รองรับคีย์ซ้ำ คีย์ต้อง implement IComparable
  • สำหรับโค้ดใหม่ แนะนำ SortedList<TKey, TValue> หรือ SortedDictionary<TKey, TValue>