상세 컨텐츠

본문 제목

Dictionary

C#

by 메타 스토리 2023. 9. 5. 09:43

본문

Dictionary는 키(Key)와 값(Value) 쌍을 사용하여 데이터를 저장하는 데이터 구조입니다. 각 키는 고유하며, 키를 사용하여 해당하는 값을 검색하거나 수정할 수 있습니다. Dictionary는 C#에서 많이 사용되며, 많은 데이터를 빠르게 검색하고 관리하는 데 유용합니다.

다음은 Dictionary의 중요한 특징과 사용법 예제입니다:

  1. 고유한 키: Dictionary 내의 각 키는 고유해야 합니다. 즉, 중복된 키를 허용하지 않습니다.
  2. 키-값 쌍: 각 키에는 하나의 값이 연결됩니다. 이 키-값 쌍을 사용하여 데이터를 저장하고 검색합니다.
  3. 데이터 추가 및 수정: 새로운 키-값 쌍을 추가하거나 기존 키의 값을 수정할 수 있습니다.
  4. 데이터 검색: 특정 키를 사용하여 해당하는 값을 검색할 수 있습니다.
  5. 순서 없음: Dictionary 내의 데이터는 특정 순서로 저장되지 않으며, 순서가 중요한 경우 SortedDictionary 또는 SortedList를 고려해야 합니다.

 

using System;
using System.Collections.Generic;

class Program
{
    static void Main()
    {
        // Dictionary 생성 (int를 키로, string을 값으로)
        Dictionary<int, string> studentNames = new Dictionary<int, string>();

        // 데이터 추가
        studentNames.Add(1, "Alice");
        studentNames.Add(2, "Bob");
        studentNames.Add(3, "Charlie");

        // 데이터 수정
        studentNames[2] = "Betty";

        // 데이터 검색
        if (studentNames.ContainsKey(1))
        {
            string name = studentNames[1];
            Console.WriteLine("Student with key 1: " + name);
        }

        // 모든 키-값 쌍에 대한 반복
        foreach (var pair in studentNames)
        {
            Console.WriteLine("Key: " + pair.Key + ", Value: " + pair.Value);
        }
    }
}

 

Student with key 1: Alice
Key: 1, Value: Alice
Key: 2, Value: Betty
Key: 3, Value: Charlie

 

using System;
using System.Collections.Generic;

class Program
{
    static void Main()
    {
        // Dictionary 생성
        Dictionary<string, int> ages = new Dictionary<string, int>();

        // 요소 추가
        ages["Alice"] = 30;
        ages["Bob"] = 25;
        ages["Charlie"] = 35;

        // 요소 접근
        int aliceAge = ages["Alice"];
        Console.WriteLine("Alice's Age: " + aliceAge);

        // 요소 수정
        ages["Bob"] = 26;
        Console.WriteLine("Bob's Updated Age: " + ages["Bob"]);

        // 요소 제거
        ages.Remove("Charlie");

        // 키-값 존재 여부 확인
        bool hasKey = ages.ContainsKey("Charlie");
        Console.WriteLine("Charlie Exists: " + hasKey);

        // Dictionary 순회
        foreach (KeyValuePair<string, int> kvp in ages)
        {
            Console.WriteLine($"{kvp.Key}: {kvp.Value} years old");
        }
    }
}

 

위 코드에서 Dictionary<string, int>는 문자열 키와 정수 값을 가지는 Dictionary를 생성합니다. 요소는 ages 변수에 추가되고, 키를 사용하여 요소에 접근하고 수정합니다. Remove 메서드를 사용하여 요소를 제거하고 ContainsKey 메서드를 사용하여 키-값의 존재 여부를 확인합니다. 마지막으로 foreach 루프를 사용하여 Dictionary의 모든 요소를 순회합니다.

 

Alice's Age: 30
Bob's Updated Age: 26
Charlie Exists: False
Alice: 30 years old
Bob: 26 years old

'C#' 카테고리의 다른 글

HashSet<T>  (0) 2023.09.05
foreach를 사용할 수 있는 일반화 클래스  (0) 2023.09.05
Stack  (0) 2023.09.05
Queue  (0) 2023.09.05
List  (0) 2023.09.05

관련글 더보기