Menu
Coddy logo textTech

Declare a HashMap

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

C#에서 HashMap에 해당하는 것은 Dictionary라고 불립니다. 이것은 효율적인 조회를 위해 키-값 쌍을 저장할 수 있게 해줍니다.

먼저, 빈 Dictionary를 생성해 보겠습니다:

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

이것은 키가 문자열(과일 이름)이고 값이 정수(수량)인 Dictionary를 생성합니다.

이제 Dictionary에 몇 가지 항목을 추가해 보겠습니다:

fruitInventory.Add("Apple", 10);
fruitInventory.Add("Banana", 15);

위 코드를 실행한 후, 우리의 fruitInventory는 다음을 포함합니다:

  • "Apple" → 10
  • "Banana" → 15

또한 다음과 같이 값을 사용하여 Dictionary를 초기화할 수 있습니다:

Dictionary<string, int> fruitInventory = new Dictionary<string, int>()
{
    { "Apple", 10 },
    { "Banana", 15 }
};
challenge icon

챌린지

중급

다음과 같은 작업을 수행하는 CreateFruitInventory라는 이름의 메서드를 만드세요:

  1. 문자열(string) 키와 정수(int) 값을 가지는 새로운 Dictionary를 생성합니다.
  2. 다음의 과일과 수량을 추가합니다: 
    • "Apple" (수량: 5)
    • "Banana" (수량: 10)
    • "Orange" (수량: 7)
  3. 생성된 Dictionary를 반환합니다.

치트 시트

C#에서 Dictionary는 효율적인 조회를 위해 키-값 쌍을 저장합니다:

빈 Dictionary 생성하기:

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

Dictionary에 항목 추가하기:

fruitInventory.Add("Apple", 10);
fruitInventory.Add("Banana", 15);

Dictionary를 값과 함께 초기화하기:

Dictionary<string, int> fruitInventory = new Dictionary<string, int>()
{
    { "Apple", 10 },
    { "Banana", 15 }
};

직접 해보기

using System;
using System.Collections.Generic;

class Program
{
    public static Dictionary<string, int> CreateFruitInventory()
    {
        // 여기에 코드를 작성하세요
    }
    
    static void Main(string[] args)
    {
        Dictionary<string, int> inventory = CreateFruitInventory();
        
        // 인벤토리 표시
        foreach (var item in inventory)
        {
            Console.WriteLine($"{item.Key}: {item.Value}");
        }
    }
}
quiz icon실력 점검

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

논리 및 흐름의 모든 레슨