Programing/C#
C# 프로그래밍의 기초 : Dictionary
유니얼
2024. 3. 3. 01:03
728x90
C#의 Dictionary<TKey, TValue> 컬렉션은 System.Collections.Generic 네임스페이스에 정의되어 있으며, 키-값 쌍으로 데이터를 저장하고 관리하는 데 사용됩니다. 각 키는 컬렉션 내에서 유일해야 하며, 이를 통해 데이터의 빠른 검색, 추가, 수정, 삭제가 가능합니다. Dictionary는 제네릭 컬렉션으로, 다양한 타입의 키와 값을 유연하게 처리할 수 있습니다.
Dictionary의 주요 특징
- 키-값 쌍: 데이터는 키와 값의 쌍으로 저장되며, 키를 통해 빠르게 해당 값에 접근할 수 있습니다.
- 제네릭 지원: 다양한 타입의 키와 값을 저장할 수 있어, 데이터 관리의 유연성을 제공합니다.
- 고유한 키: 키는 컬렉션 내에서 고유해야 하며, 중복된 키로 새 값을 추가하려 할 때 예외가 발생합니다.
- 동적 크기 조정: 요소의 추가 및 제거에 따라 컬렉션의 크기가 동적으로 조절됩니다.
주요 메서드 및 속성
- Add(TKey key, TValue value): 새 키-값 쌍을 딕셔너리에 추가합니다.
- Remove(TKey key): 지정된 키를 가진 요소를 제거합니다.
- ContainsKey(TKey key): 딕셔너리에 특정 키가 있는지 확인합니다.
- TryGetValue(TKey key, out TValue value): 특정 키에 해당하는 값을 가져오려 시도하며, 성공 여부를 반환합니다.
- Count: 딕셔너리에 있는 키-값 쌍의 수를 반환합니다.
Dictionary 사용 예제
using System;
class Program
{
static void Main(string[] args)
{
// 문자열 키와 문자열 값을 가지는 Dictionary 생성
Dictionary<string, string> capitals = new Dictionary<string, string>();
// 키-값 쌍 추가
capitals.Add("South Korea", "Seoul");
capitals.Add("United States", "Washington D.C.");
capitals.Add("United Kingdom", "London");
// 키를 통한 값 접근
Console.WriteLine($"The capital of South Korea is {capitals["South Korea"]}"); // 출력: Seoul
// 딕션어리 순회
// 딕션어리에 있는 모든 Value(값)을 가져온다.
foreach (string str in capitals.Values)
{
Console.WriteLine(str);
}
foreach (string str in capitals.Keys)
{
Console.WriteLine(str);
}
foreach (KeyValuePair<string, string> str in capitals)
{
Console.WriteLine(str.Key + " : " + str.Value);
}
// 키 존재 여부 확인
if (capitals.ContainsKey("France"))
{
Console.WriteLine("Dictionary has key : France");
}
else
{
Console.WriteLine("Dictionary has Not key : France");
}
// 값 존재 여부 확인
if (capitals.ContainsValue("Seoul"))
{
Console.WriteLine("Dictionary has value : Seoul");
}
else
{
Console.WriteLine("Dictionary has Not value : Seoul");
}
// 키 - 값 쌍으로 존재 여부 확인
if (capitals.Contains(new KeyValuePair<string, string>("South Korea", "Seoul")))
{
Console.WriteLine("Dictionary has KeyValuePair : South Korea : Seoul");
}
else
{
Console.WriteLine("Dictionary has Not KeyValuePair : South Korea : Seoul");
}
// 키에 해당하는 값 가져오기
if (capitals.ContainsKey("United States"))
{
Console.WriteLine($"The capital of the United States is {capital}");
}
string capital;
if (capitals.TryGetValue("United Kingdom", out capital))
{
Console.WriteLine($"The capital of the United Kingdom is {capital}");
}
}
}
위 예제는 Dictionary<string, string>을 사용하여 국가 이름과 수도를 키-값 쌍으로 저장하고, 키를 통해 값에 접근하는 방법을 보여줍니다. 딕셔너리의 순회, 키의 존재 여부 확인, 키에 해당하는 값의 검색 등 다양한 작업을 수행할 수 있습니다.
결론
Dictionary<TKey, TValue>는 C# 프로그래밍에서 데이터를 효율적으로 관리하고 검색할 수 있는 강력한 도구입니다. 키-값 쌍의 저장 방식은 데이터 접근 시간을 최소화하며, 제네릭을 통한 유연한 데이터 타입 처리는 다양한 상황에서의 사용을 가능하게 합니다. 따라서, 복잡한 데이터 구조를 관리하거나 빠른 데이터 검색이 필요한 경우 Dictionary의 사용을 고려해볼 수 있습니다.
반응형