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

Phương thức Dictionary.ContainsValue() trong C#


Phương thức Dictionary.ContainsValue() trong C# được sử dụng để kiểm tra xem Dictionary<TKey, TValue> có chứa một giá trị cụ thể hay không.

Cú pháp

public bool ContainsValue(TValue value);

Tham số:

  • value: Giá trị cần tìm kiếm

Ví dụ 1: Giá trị tồn tại

using System;
using System.Collections.Generic;

public class Demo
{
    public static void Main()
    {
        Dictionary dict = new Dictionary();
        dict.Add("One", "John");
        dict.Add("Two", "Tom");
        dict.Add("Three", "Jacob");
        dict.Add("Four", "Kevin");
        dict.Add("Five", "Nathan");
        
        Console.WriteLine("Số lượng phần tử = " + dict.Count);
        Console.WriteLine("\nCác cặp Key/Value...");
        
        foreach (KeyValuePair 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 Key/Value...");
        Console.WriteLine("Số lượng phần tử hiện tại = " + dict.Count);
    }
}

Kết quả

Số lượng phần tử = 5
Các cặp Key/Value...
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 Key/Value...
Số lượng phần tử hiện tại = 0

Ví dụ 2: Giá trị không tồn tại

using System;
using System.Collections.Generic;

public class Demo
{
    public static void Main()
    {
        Dictionary dict = new Dictionary();
        dict.Add("One", "Chris");
        dict.Add("Two", "Steve");
        dict.Add("Three", "Messi");
        dict.Add("Four", "Ryan");
        dict.Add("Five", "Nathan");
        
        Console.WriteLine("Số lượng phần tử = " + dict.Count);
        Console.WriteLine("\nCác cặp Key/Value...");
        
        foreach (KeyValuePair 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 Key/Value...");
        Console.WriteLine("Số lượng phần tử hiện tại = " + dict.Count);
    }
}

Kết quả

Số lượng phần tử = 5
Các cặp Key/Value...
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 Key/Value...
Số lượng phần tử hiện tại = 0

Hiệu suất: ContainsValue có độ phức tạp O(n) vì phải duyệt qua tất cả giá trị, khác với ContainsKey là O(1) nhờ cơ chế hash.