본문 바로가기
개발/C#

C# Dictionary 딕셔너리 사용법 및 정렬 예시 간단 구현

by SPNK 2023. 10. 20.
반응형

 딕셔너리 (Dictionary)

HashMap과 유사한 역할을 하며 키 기반으로 값을 저장하고 검색하는데 사용됩니다.

 

  • 생성
Dictionary<string, int> myDictionary = new Dictionary<string, int>();

 

  • 요소 추가 및 업데이트
myDictionary["one"] = 1;
myDictionary["two"] = 2;
myDictionary["three"] = 3;
myDictionary["one"] = 11; // "one" 키에 연결된 값 업데이트

 

  • 요소 제거
myDictionary.Remove("two");

 

  • 값 가져오기
int value = myDictionary["three"]; // value에는 3이 저장됩니다.

 

  • 요소 루프
foreach (var kvp in myDictionary)
{
    string key = kvp.Key;
    int value = kvp.Value;
}

 

  • 오름차순 정렬
dic = dic.OrderBy(x => x.Key).ToDictionary(x => x.Key, x => x.Value);

 

  • 내림차순 정렬
dic = dic.OrderByDescending(x => x.Key).ToDictionary(x => x.Key, x => x.Value);

 

반응형

댓글