728x90
반응형
딕셔너리(Dictionary)는 데이터를 키-값 쌍으로 저장하는 데이터 구조입니다.
이를 사용하여 각 키(Key)에 대응하는 값을(Value) 매핑할 수 있습니다.
딕셔너리는 일반적으로 빠른 데이터 조회를 위해 사용되며, 특정 키에 대응하는 값을 빠르게 찾을 수 있습니다.
딕셔너리의 기본구조는 아래 코드와 같습니다.
Dictionary<Key, Value> dictionary = new Dictionary<Key, Value>();
현재 예제 프로젝트의 딕셔너리 선언은 다음과 같습니다.
Dictionary<int, string> dictionary = new Dictionary<int, string>();
딕셔너리에 버튼이벤트를 이용하여 키, 값을 추가해보겠습니다.
private void button_Click(object sender, RoutedEventArgs e)
{
dictionary.Add(1, "개발자1");
dictionary.Add(2, "개발자2");
dictionary.Add(3, "개발자3");
text_add.Text = dictionary.Count.ToString();
}

Dictionary의 객체명.count한다면 현재 Dictionary에 들어있는 키가 몇개인지 확인합니다.
딕셔너리에 버튼이벤트를 이용하여 특정 키를 찾아 키의 값을 Text에 출력해보겠습니다.
private void button_find_Click(object sender, RoutedEventArgs e)
{
if (dictionary.ContainsKey(1))
{
text_find.Text = dictionary[1];
}
else
{
MessageBox.Show("해당 키값이 없습니다.");
}
}
Dictionary의 키 "1"에 해당하는 값을 찾아보겠습니다.

다음은 딕셔너리에 버튼이벤트를 이용하여 특정 키를 찾아 키를 삭제해보겠습니다.
private void button_delete_Click(object sender, RoutedEventArgs e)
{
dictionary.Remove(1);
text_add.Text = dictionary.Count.ToString();
}

삭제버튼 클릭 후 찾기 버튼을 클릭하면 이미 키값은 삭제되었기 때문에 해당 메시지 박스창이 나옵니다.
728x90
반응형
'C#' 카테고리의 다른 글
C# Serial 통신 (0) | 2023.07.24 |
---|