Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> C#

Lấy các giá trị trong SortedList C#

Giới thiệu

SortedList lưu trữ cặp khóa-giá trị được sắp xếp theo khóa. Thuộc tính Values trả về ICollection chứa tất cả giá trị theo thứ tự khóa. Thuộc tính Keys trả về tập hợp khóa.

Ví dụ 1: Lấy Values và Keys với khóa số

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);
        }
    }
}

Kết quả

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

Ví dụ 2: Lấy Values và Keys với khóa chuỗi

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);
        }
    }
}

Kết quả

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

Lưu ý quan trọng

  • Values và Keys trả về view (không sao chép dữ liệu)
  • Thay đổi SortedList gốc → View phản ánh ngay lập tức
  • Thứ tự giá trị tương ứng với thứ tự khóa đã sắp xếp
  • Không thể sửa đổi Values/Keys trực tiếp (chỉ đọc)

So sánh với SortedList<TKey, TValue> (Generic)

// Non-generic (System.Collections)
SortedList list = new SortedList();
list.Add("A", 1);
ICollection values = list.Values; // object

// Generic (System.Collections.Generic) - KHUYẾN DÙNG
SortedList<string, int> list2 = new SortedList<string, int>();
list2.Add("A", 1);
ICollection<int> values2 = list2.Values; // int - type safe
ICollection<string> keys2 = list2.Keys;  // string - type safe