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

Lấy ICollection chứa values trong OrderedDictionary C#

Giới thiệu

Để lấy tập hợp các giá trị (values) trong OrderedDictionary dưới dạng ICollection, sử dụng thuộc tính Values. OrderedDictionary lưu trữ cặp key-value và duy trì thứ tự chèn (insertion order).

Ví dụ 1: Lấy values và copy sang mảng

using System;
using System.Collections;
using System.Collections.Specialized;

public class Demo {
    public static void Main() {
        OrderedDictionary dict = new OrderedDictionary();
        dict.Add("1", "One");
        dict.Add("2", "Two");
        dict.Add("3", "Three");
        dict.Add("4", "Four");
        dict.Add("5", "Five");
        dict.Add("6", "Six");
        dict.Add("7", "Seven");
        dict.Add("8", "Eight");

        // Lấy ICollection chứa values
        ICollection values = dict.Values;

        // Copy sang mảng string
        string[] strValues = new string[dict.Count];
        values.CopyTo(strValues, 0);

        Console.WriteLine("Hiển thị các giá trị...");
        for (int i = 0; i < dict.Count; i++) {
            Console.WriteLine(strValues[i]);
        }
    }
}

Đầu ra ví dụ 1

Hiển thị các giá trị...
One
Two
Three
Four
Five
Six
Seven
Eight

Ví dụ 2: OrderedDictionary với key string có ý nghĩa

using System;
using System.Collections;
using System.Collections.Specialized;

public class Demo {
    public static void Main() {
        OrderedDictionary dict = new OrderedDictionary();
        dict.Add("One", "John");
        dict.Add("Two", "Tim");
        dict.Add("Three", "Katie");
        dict.Add("Four", "Andy");
        dict.Add("Five", "Gary");
        dict.Add("Six", "Amy");

        ICollection values = dict.Values;
        string[] strValues = new string[dict.Count];
        values.CopyTo(strValues, 0);

        Console.WriteLine("Hiển thị các giá trị...");
        for (int i = 0; i < dict.Count; i++) {
            Console.WriteLine(strValues[i]);
        }
    }
}

Đầu ra ví dụ 2

Hiển thị các giá trị...
John
Tim
Katie
Andy
Gary
Amy

Đặc điểm OrderedDictionary

  • Kết hợp đặc điểm Hashtable (tra cứu key O(1)) và ArrayList (thứ tự chèn).
  • Key không bắt buộc unique (khác Hashtable/Dictionary), nhưng khuyến nghị unique.
  • Key và Value đều là object (non-generic).
  • Namespace: System.Collections.Specialized.

Các thành viên quan trọng

Thành viênKiểuMô tả
KeysICollectionTập hợp các key (theo thứ tự chèn)
ValuesICollectionTập hợp các value (theo thứ tự chèn)
Item[key]objectGetter/setter value bằng key
Item[index]objectGetter/setter value bằng index (0-based)
Add(key, value)voidThêm cặp key-value
Remove(key)voidXóa theo key
RemoveAt(index)voidXóa theo index
Insert(index, key, value)voidChèn tại vị trí index
Clear()voidXóa tất cả

Lưu ý khi dùng Values

  • Values trả về ICollection read-only view, không thể Add/Remove trực tiếp.
  • Thứ tự values tương ứng với thứ tự keys (insertion order).
  • CopyTo(array, index) copy values vào mảng đích.
  • Để lặp: foreach (var val in dict.Values) hoặc dùng enumerator.

So sánh với Dictionary<TKey, TValue>

Đặc điểmOrderedDictionaryDictionary<TKey, TValue>
Thứ tựInsertion orderKhông đảm bảo (từ .NET Core 3.7+ giữ insertion order)
GenericKhông (object)Có (type-safe)
Key uniqueKhông bắt buộcBắt buộc
Index accessCó (Item[index])Không
NamespaceSystem.Collections.SpecializedSystem.Collections.Generic

Khuyến nghị hiện đại

Trong .NET Core/.NET 5+, Dictionary<TKey, TValue> đã giữ insertion order. Nên dùng Dictionary<string, string> thay vì OrderedDictionary cho type safety và hiệu năng tốt hơn.