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

Thuộc tính Dictionary.Values trong C#

Thuộc tính Dictionary.Values trong C# được dùng để lấy tất cả các giá trị trong Dictionary.

Cú pháp

public System.Collections.Generic.Dictionary<TKey, TValue>.ValueCollection Values { get; }

Ví dụ 1: Dictionary với khóa kiểu string

using System;
using System.Collections.Generic;
public class Demo {
    public static void Main() {
        Dictionary<string, string> dict = new Dictionary<string, string>();
        dict.Add("One", "Kagido");
        dict.Add("Two", "Ngidi");
        dict.Add("Three", "Devillers");
        dict.Add("Four", "Smith");
        dict.Add("Five", "Warner");
        Console.WriteLine("Số lượng phần tử = " + dict.Count);
        Console.WriteLine("\nCác cặp khóa/giá trị...");
        foreach (KeyValuePair<string, string> res in dict) {
            Console.WriteLine("Khóa = {0}, Giá trị = {1}", res.Key, res.Value);
        }
        Console.Write("\nTất cả các giá trị..\n");
        Dictionary<string, string>.ValueCollection allValues = dict.Values;
        foreach (string str in allValues) {
            Console.WriteLine("Giá trị = {0}", str);
        }
    }
}

Kết quả

Số lượng phần tử = 5
Các cặp khóa/giá trị...
Khóa = One, Giá trị = Kagido
Khóa = Two, Giá trị = Ngidi
Khóa = Three, Giá trị = Devillers
Khóa = Four, Giá trị = Smith
Khóa = Five, Giá trị = Warner
Tất cả các giá trị..
Giá trị = Kagido
Giá trị = Ngidi
Giá trị = Devillers
Giá trị = Smith
Giá trị = Warner

Ví dụ 2: Dictionary với khóa kiểu int

using System;
using System.Collections.Generic;
public class Demo {
    public static void Main() {
        Dictionary<int, string> dict = new Dictionary<int, string>();
        dict.Add(1, "Kagido");
        dict.Add(2, "Ngidi");
        dict.Add(3, "Devillers");
        Console.WriteLine("Số lượng phần tử = " + dict.Count);
        Console.WriteLine("\nCác cặp khóa/giá trị...");
        foreach (KeyValuePair<int, string> res in dict) {
            Console.WriteLine("Khóa = {0}, Giá trị = {1}", res.Key, res.Value);
        }
        Console.Write("\nTất cả các giá trị..\n");
        Dictionary<int, string>.ValueCollection allValues = dict.Values;
        foreach (string str in allValues) {
            Console.WriteLine("Giá trị = {0}", str);
        }
    }
}

Kết quả

Số lượng phần tử = 3
Các cặp khóa/giá trị...
Khóa = 1, Giá trị = Kagido
Khóa = 2, Giá trị = Ngidi
Khóa = 3, Giá trị = Devillers
Tất cả các giá trị..
Giá trị = Kagido
Giá trị = Ngidi
Giá trị = Devillers