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

Kiểm tra Dictionary chứa giá trị cụ thể trong C#

Ví dụ 1

Sử dụng ContainsValue:

using System;
using System.Collections.Generic;

public class Demo {
    public static void Main() {
        Dictionary<string, string> dict = new Dictionary<string, string>();
        dict.Add("One", "John");
        dict.Add("Two", "Tom");
        dict.Add("Three", "Jacob");
        dict.Add("Four", "Kevin");
        dict.Add("Five", "Nathan");
        
        Console.WriteLine("Số phần tử = " + dict.Count);
        Console.WriteLine("\nCác cặp khóa/giá trị...");
        foreach(KeyValuePair<string, string> res in dict) {
            Console.WriteLine("Key = {0}, Value = {1}", res.Key, res.Value);
        }
        
        if (dict.ContainsValue("Kevin"))
            Console.WriteLine("Tìm thấy giá trị!");
        else
            Console.WriteLine("Giá trị không có trong dictionary!");
        
        dict.Clear();
        Console.WriteLine("Đã xóa các cặp khóa/giá trị...");
        foreach(KeyValuePair<string, string> res in dict) {
            Console.WriteLine("Key = {0}, Value = {1}", res.Key, res.Value);
        }
        
        Console.WriteLine("Số phần tử hiện tại = " + dict.Count);
    }
}

Kết quả

Số phần tử = 5
Các cặp khóa/giá trị...
Key = One, Value = John
Key = Two, Value = Tom
Key = Three, Value = Jacob
Key = Four, Value = Kevin
Key = Five, Value = Nathan
Tìm thấy giá trị!
Đã xóa các cặp khóa/giá trị...
Số phần tử hiện tại = 0

Ví dụ 2

Tìm giá trị không tồn tại:

using System;
using System.Collections.Generic;

public class Demo {
    public static void Main() {
        Dictionary<string, string> dict = new Dictionary<string, string>();
        dict.Add("One", "Chris");
        dict.Add("Two", "Steve");
        dict.Add("Three", "Messi");
        dict.Add("Four", "Ryan");
        dict.Add("Five", "Nathan");
        
        Console.WriteLine("Số phần tử = " + dict.Count);
        Console.WriteLine("\nCác cặp khóa/giá trị...");
        foreach(KeyValuePair<string, string> res in dict) {
            Console.WriteLine("Key = {0}, Value = {1}", res.Key, res.Value);
        }
        
        if (dict.ContainsValue("Angelina"))
            Console.WriteLine("Tìm thấy giá trị!");
        else
            Console.WriteLine("Giá trị không có trong dictionary!");
        
        dict.Clear();
        Console.WriteLine("Đã xóa các cặp khóa/giá trị...");
        Console.WriteLine("Số phần tử hiện tại = " + dict.Count);
    }
}

Kết quả

Số phần tử = 5
Các cặp khóa/giá trị...
Key = One, Value = Chris
Key = Two, Value = Steve
Key = Three, Value = Messi
Key = Four, Value = Ryan
Key = Five, Value = Nathan
Giá trị không có trong dictionary!
Đã xóa các cặp khóa/giá trị...
Số phần tử hiện tại = 0