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

Lấy ICollection chứa các giá trị trong HybridDictionary trong C#

Giới thiệu

Để lấy một ICollection chứa các giá trị trong HybridDictionary, bạn có thể sử dụng thuộc tính Values kết hợp với phương thức CopyTo để sao chép vào mảng. Dưới đây là các ví dụ minh họa.

Ví dụ 1

using System;
using System.Collections.Specialized;

public class Demo
{
    public static void Main()
    {
        HybridDictionary dict = new HybridDictionary();
        dict.Add("One", "Katie");
        dict.Add("Two", "Andy");
        dict.Add("Three", "Gary");
        dict.Add("Four", "Mark");
        dict.Add("Five", "Marie");
        dict.Add("Six", "Sam");
        dict.Add("Seven", "Harry");
        dict.Add("Eight", "Kevin");
        dict.Add("Nine", "Ryan");

        String[] strArr = new String[dict.Count];
        dict.Values.CopyTo(strArr, 0);

        for (int i = 0; i < dict.Count; i++)
            Console.WriteLine(strArr[i]);
    }
}

Kết quả

Kevin
Harry
Mark
Gary
Katie
Marie
Sam
Andy
Ryan

Ví dụ 2

using System;
using System.Collections.Specialized;

public class Demo
{
    public static void Main()
    {
        HybridDictionary dict = new HybridDictionary();
        dict.Add("1", "A");
        dict.Add("2", "B");
        dict.Add("3", "C");
        dict.Add("4", "D");
        dict.Add("5", "E");
        dict.Add("6", "F");

        String[] strArr = new String[dict.Count];
        dict.Values.CopyTo(strArr, 0);

        for (int i = 0; i < dict.Count; i++)
            Console.WriteLine(strArr[i]);
    }
}

Kết quả

A
B
C
D
E
F

Lưu ý: Thứ tự các phần tử trong HybridDictionary không được đảm bảo, do đó kết quả có thể khác nhau giữa các lần chạy.