본문 바로가기

[C#] Dictionary 사용하기

I'm 영서 2022. 9. 5.
반응형

Key를 가진 List를 사용해야 하는 경우가 종종 발생한다.

 

JAVA의 Map과 같은 형태라고 생각하면 될거같다.. 

 

Dictionary는 Key와 Value를 가진 컬렉션으로 한 개의 중복되지 않는 Key와 Value를 가진다.. 

//선언 및 초기화
Dictionary < TKey, TValue> dic = new Dictionary < TKey, TValue>()

// 일반적인 자료형 사용가능
Dictionary < string,  int > dic = null 

// 컬렉션 사용 가능
Dictionary < List<string>,  string > dic = null 

// 컬렉션 Key, Value 사용가능..
Dictionary < List<string>,  List<string> > dic = null

// 이런것까지 다 된다!
Dictionary < Dictionary < List<string>,  List<string> > dic  ,  List<string> > dic  = null

Dictionary 속성

주로 사용하게 되는 매서드들에 대한 정리이다. 이것만 알아도 대충 사용은 가능.. 

// Add
dic.Add(/*key, value*/)

// Count 
// Key/Value 쌍 수
dic.Count()

// Item[TKey] 
// 지정된 Key의 연결된 Values
foreach(object key in dic.Keys){
    value = dic[key] 
}

// Keys 
// TKey에 해당하는 컬렉션을 가져온다.
foreach (object o in dic.Keys) {}

// Values 
// TValue에 해당하는 컬렉션을 가져온다.
foreach (object o in dic.Values) {}

 

반응형

댓글