개발 공부/C# 기초

[C# 기초] Dictionary(매개변수, 네임스페이스, 선언, foreach)

아밍나 2022. 10. 13. 17:30
728x90

Dictionary 클래스

Dictionary<TKey, TValue>
- 키와 값의 컬렉션을 나타낸다.

- 매개변수

TKey: Dictionary Key의 형식(Type)
TValue: Dictionary Value의 형식(Type)

- 네임스페이스

System.Collections.Generic;

- Dictionary 선언방법

Dictionary<Key 데이터형, Value 데이터형> 오브젝트명 = new Dictionary<Key 데이터형, Value 데이터형>()
//Dictionary 클래스를 인스턴스화하여 변수 a에 대입
const a = new Dictionary<string, string>();
//선언, 정의, 초기화 동시에
const Obj = new Dictionary<string, string>()
            {
                {key0, value0},
                {key1, value1}.
                ...
            };

- 요소 추가

오브젝트명.Add("Key", "Value");

→ Add 메서드 사용.

→ Key와 Value는 Dictionary<TKey, TValue>의 Type과 일치해야 한다.

- foreach

using System;
using System.Collections.Generic;

const myDictionary = new Dictionary<string, string>();
foreach( KeyValuePair<string, string> D in myDictionary )
{
    Console.WriteLine("Key = {0}, Value = {1}", D.Key, D.Value);
}

→ Key와 Value 요소를 얻을 수 있다.

→ KeyValuePair 구조체 사용

 

더보기

- KeyValuePair 구조체

설정하거나 검색할 수 있는 키/값 쌍을 정의.

- 네임스페이스

System.Collections.Generic;

 

 

 

 

 

 

 

 

 

 


참고자료)

https://learn.microsoft.com/ko-kr/dotnet/api/system.collections.generic.dictionary-2?view=net-6.0 

 

Dictionary<TKey,TValue> 클래스 (System.Collections.Generic)

키와 값의 컬렉션을 나타냅니다.

learn.microsoft.com

https://engineer-mole.tistory.com/174

 

[C#] C#의 Dictionary (사전형) 데이터 사용법

Dictionary이란  Dictionary에서는 Key라고 불리는 인덱스 번호를 대신해 사용하는 명칭과 Value라고 불리는 값을 세트로 다룬다. 참고로 Key와 Vlaue 세트로 다루는 배열을 "연관 배열"이라고 부른다.  C#

engineer-mole.tistory.com

https://learn.microsoft.com/ko-kr/dotnet/api/system.collections.generic.keyvaluepair-2?view=net-6.0 

 

KeyValuePair<TKey,TValue> 구조체 (System.Collections.Generic)

설정하거나 검색할 수 있는 키/값 쌍을 정의합니다.

learn.microsoft.com

 

728x90
반응형