Menu
CoddyTech

Kiểm tra khóa có tồn tại không

Thuộc phần Logic và luồng chương trình trong hành trình C# của Coddy. Bài học 48 trên 66.

Để kiểm tra xem một khóa có tồn tại trong HashMap (Dictionary trong C#) hay không, bạn có thể dùng phương thức (method) ContainsKey().

Đầu tiên, hãy tạo một từ điển:

Dictionary<string, int> ages = new Dictionary<string, int>();

Thêm một số cặp khóa-giá trị:

ages.Add("John", 25);
ages.Add("Mary", 30);

Bây giờ, hãy kiểm tra xem khóa có tồn tại không:

bool exists = ages.ContainsKey("John");

Sau khi chạy đoạn code trên, biến exists sẽ có giá trị true.

Bạn có thể dùng cách này trong câu lệnh điều kiện:

if (ages.ContainsKey("John"))
{
    Console.WriteLine("John's age is in the dictionary");
}
else
{
    Console.WriteLine("John's age is not in the dictionary");
}
challenge icon

Thử thách

Dễ

Tạo một phương thức có tên CheckKeyExists nhận hai đối số:

  • Một Dictionary<string, int> (từ điển)
  • Một chuỗi (khóa) cần kiểm tra

Phương thức này cần kiểm tra xem khóa có tồn tại trong từ điển hay không và in ra:

  • "Key exists" nếu tìm thấy khóa
  • "Key does not exist" nếu không tìm thấy khóa

Tự làm thử

using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;
class Program
{
    public static void CheckKeyExists(Dictionary<string, int> dictionary, string key)
    {
        // Viết code ở đây
    }
    
    static void Main(string[] args)
    {
        Dictionary<string, int> inventory = new Dictionary<string, int>();
        
        // Đọc đầu vào của kho hàng, chấp nhận cả định dạng JSON và định dạng từng dòng
        string firstLine = Console.ReadLine();
        
        // Kiểm tra xem đầu vào có ở định dạng JSON không
        if (firstLine != null && firstLine.StartsWith("{") && firstLine.EndsWith("}"))
        {
            try
            {
                // Xử lý đầu vào JSON
                string jsonContent = firstLine.Substring(1, firstLine.Length - 2);
                
                // Tách theo các dấu phẩy nằm ngoài dấu ngoặc kép
                string pattern = @",(?=(?:[^""]*""[^""]*"")*[^""]*$)";
                string[] entries = Regex.Split(jsonContent, pattern);
                
                foreach (string entry in entries)
                {
                    // Trích xuất khóa và giá trị bằng regex
                    Match match = Regex.Match(entry, @"""([^""]+)""\s*:\s*(\d+)");
                    if (match.Success)
                    {
                        string keyMatch = match.Groups[1].Value;
                        int valueMatch = int.Parse(match.Groups[2].Value);
                        inventory.Add(keyMatch, valueMatch);
                    }
                }
                
                // Reading the key to check directly
                string keyToCheck = Console.ReadLine();
                CheckKeyExists(inventory, keyToCheck);
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Error parsing input: {ex.Message}");
            }
        }
        else
        {
            // Process original line-by-line format
            string line = firstLine;
            
            // Read lines until an empty line is entered
            while (!string.IsNullOrEmpty(line))
            {
                try
                {
                    string[] parts = line.Split(':');
                    if (parts.Length == 2)
                    {
                        inventory.Add(parts[0], int.Parse(parts[1]));
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine($"Error parsing line: {ex.Message}");
                }
                
                // Read next line
                line = Console.ReadLine();
            }
            
            // Reading the key to check
            string keyToCheck = Console.ReadLine();
            CheckKeyExists(inventory, keyToCheck);
        }
    }
}
quiz iconTự kiểm tra

Bài học này có một bài trắc nghiệm ngắn. Bắt đầu bài học để trả lời và theo dõi tiến độ.

Tất cả bài học trong Logic và luồng chương trình

Tự luyện tập: Trình biên dịch C# online