Menu
Coddy logo textTech

HashMap Methods

Coddy C# 여정의 논리 및 흐름 섹션에 포함된 레슨 — 66개 중 52번째.

HashMap 메서드는 사전 데이터를 다루는 강력한 방법을 제공합니다. 몇 가지 일반적인 메서드를 살펴보죠:

딕셔너리에 키가 존재하는지 확인:

Dictionary<string, int> inventory = new Dictionary<string, int>();
inventory.Add("apples", 25);

bool hasApples = inventory.ContainsKey("apples");
// hasApples will be true

딕셔너리에서 모든 키 가져오기:

Dictionary<string, int> scores = new Dictionary<string, int>();
scores.Add("Alice", 95);
scores.Add("Bob", 87);

// 모든 키 가져오기
Dictionary<string, int>.KeyCollection keys = scores.Keys;
foreach (string name in keys)
{
    Console.WriteLine(name);
}

딕셔너리에서 모든 값 가져오기:

// 모든 값 가져오기
Dictionary<string, int>.ValueCollection values = scores.Values;
foreach (int score in values)
{
    Console.WriteLine(score);
}

딕셔너리에서 항목 제거:

scores.Remove("Bob");
// Dictionary now only contains Alice's score

모든 항목 지우기:

scores.Clear();
// 이제 Dictionary는 비어 있습니다

딕셔너리의 항목 수를 .Count를 사용하여 가져오기:

Dictionary<string, int> scores = new Dictionary<string, int>();
scores.Add("Alice", 95);
scores.Add("Bob", 87);

int total = scores.Count;
Console.WriteLine(total);
// Output: 2
challenge icon

챌린지

중급

ProcessDictionary라는 이름의 메서드를 생성하여 Dictionary<string, int>를 인수로 받고 다음 작업을 수행하세요:

  1. Keys:를 출력한 후 모든 키를 한 줄에 하나씩 출력하세요
  2. Values:를 출력한 후 모든 값을 한 줄에 하나씩 출력하세요
  3. 딕셔너리에 "total" 키가 포함되어 있는지 확인하고 Contains 'total': True 또는 Contains 'total': False를 출력하세요
  4. 존재하는 경우 "temp" 키를 제거하세요
  5. 이 작업 후 딕셔너리의 항목 수를 Count: 다음에 출력하세요 (딕셔너리의 .Count 속성을 사용하세요)

치트 시트

ContainsKey()를 사용하여 키가 존재하는지 확인:

bool hasKey = dictionary.ContainsKey("keyName");

딕셔너리에서 모든 키 가져오기:

Dictionary<string, int>.KeyCollection keys = dictionary.Keys;
foreach (string key in keys)
{
    Console.WriteLine(key);
}

딕셔너리에서 모든 값 가져오기:

Dictionary<string, int>.ValueCollection values = dictionary.Values;
foreach (int value in values)
{
    Console.WriteLine(value);
}

Remove()를 사용하여 항목 제거:

dictionary.Remove("keyName");

Clear()를 사용하여 모든 항목 지우기:

dictionary.Clear();

.Count를 사용하여 항목 수 가져오기:

int count = dictionary.Count;

직접 해보기

using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;

class Program
{
    static void ProcessDictionary(Dictionary<string, int> dict)
    {
        // 여기에 코드를 작성하세요
    }
    // 메인 코드는 무시하세요, 문자열을 HashMap으로 변환합니다
    static void Main(string[] args)
    {
        Dictionary<string, int> inputDict = new Dictionary<string, int>();
        
        // Read first line to check if it's JSON format
        string firstLine = Console.ReadLine();
        
        // Check if input is in JSON format
        if (firstLine != null && firstLine.StartsWith("{") && firstLine.EndsWith("}"))
        {
            try
            {
                // Process JSON input
                string jsonContent = firstLine.Substring(1, firstLine.Length - 2);
                
                // Split by commas that are not inside quotes
                string pattern = @",(?=(?:[^""]*""[^""]*"")*[^""]*$)";
                string[] entries = Regex.Split(jsonContent, pattern);
                
                foreach (string entry in entries)
                {
                    // Extract key and value using 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);
                        inputDict.Add(keyMatch, valueMatch);
                    }
                }
                
                ProcessDictionary(inputDict);
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Error parsing input: {ex.Message}");
            }
        }
        else
        {
            try
            {
                // Process traditional input format
                int n = int.Parse(firstLine);
                
                for (int i = 0; i < n; i++)
                {
                    string[] pair = Console.ReadLine().Split(':');
                    string key = pair[0];
                    int value = int.Parse(pair[1]);
                    inputDict.Add(key, value);
                }
                
                ProcessDictionary(inputDict);
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Error parsing input: {ex.Message}");
            }
        }
    }
}
quiz icon실력 점검

이 레슨에는 짧은 퀴즈가 포함되어 있습니다. 레슨을 시작해 문제를 풀고 진행 상황을 기록하세요.

논리 및 흐름의 모든 레슨