C#에서 Dictonary를 활용할 때 자주 사용하던 함수 등에 대해 설명합니다.
* Dictionary 클래스 사용 시
//Dictionary 클래스를 사용하기 위한 네임스페이스
using System.Collections.Genetric;
* Dictionary의 선언, 정의, 초기화
//선언과 정의
var tempDic = new Dictonary<string, string>();
//선언과 정의2
Dictionary<string, string> tempDic2 = new Dictionary<string, string>();
//선언과 정의, 초기화
var tempDic = new Dictonary<string, string>(
{ "key1", "value1" },
{ "key2", "value2" },
{ "key3", "value3" }
);
* Dictionary에 Add로 요소 추가/삭제
var tempDic = new Dictionary<string, string>();
//요소를 추가합니다.
tempDic.Add("key1", "value1");
tempDic.Add("key2", "value2");
tempDic.Add("key3", "value3");
//요소를 삭제합니다.
tempDic.Remove("key1");
tempDic.Remove("key2");
tempDic.Remove("key3");
* Dictionary의 Key값이 존재하는 지 검사
if(tempDic.ContainsKey("key1"))
{
Console.WriteLine("키가 존재합니다.");
}
else
{
Console.WriteLine("키가 없습니다.");
}
* Dictionary의 Key값으로 value값을 추출, 불러오기
//단순 추출, 키값이 없으면 에러(KeyNotFoundException) 발생
Console.WriteLine(tempDic["key1"]);
//안전하게 추출하기
string result = "";
if(tempDic.TryGetValue("key1", out string result))
{
//키값이 존재할 때
Console.WriteLine(result);
}
else
{
//키값이 없을 때
Console.WriteLine("키값이 없습니다");
}
* foreach문으로 모두 추출, 불러오기
//KEY값과 VALUE값 모두를 출력합니다.
foreach(KeyValuePair<string, string> dicItem in tempDic) {
Console.WriteLine("key:{0}, value:{1}]", dicItem.Key, dicItem.Value);
}
//VALUE값만 출력합니다.
foreach(string val in tempDic.Values) {
Console.WriteLine(val);
}
* Dictionary의 마지막 Key값, 마지막 Value를 추출, 불러오기
//마지막에 추가된 KEY값
Console.WriteLine(tempDic.Keys.Last());
//마지막에 추가된 KEY값
Console.WriteLine(tempDic.Values.Last());
* Dictionary의 가장 큰 Key값, 가장 큰 Value값을 추출, 불러오기
//가장 큰 Key값
Console.WriteLine(tempDic.Keys.Max());
//가장 큰 Value값
Console.WriteLine(tempDic.Values.Max());
'Windows Application' 카테고리의 다른 글
영수증 프린터 출력 테스트 프로그램 (0) | 2025.02.14 |
---|---|
파일 완전 삭제 프로그램 (HotEraser) (0) | 2025.02.14 |
윈도우10,11 업데이트 차단 (Windows_Update_Blocker) (0) | 2025.02.14 |
드라이버 서명 사용 안함 (DSE Disabler) (0) | 2022.04.18 |
[SQL Server 2019 Express] 필수 파일을 다운로드할 수 없습니다 에러 해결 방법! (0) | 2022.04.18 |