관리 메뉴

Kinesis´s Open Document

C# - 문자열(String)을 인덱스 키(Key)로 활용하여 값 처리 하기 (Dictionary) 본문

MEMO/기술 자료/C# Language

C# - 문자열(String)을 인덱스 키(Key)로 활용하여 값 처리 하기 (Dictionary)

Kinesis 2012. 3. 21. 15:40
반응형


프로그래밍을 하다보면 인덱스를 이용하여 간단하게 값을 가져오거나 설정하여 사용하는 경우가 많다. 그 대표적인 객체 중 하나가 바로 배열이다. 하지만 배열은 기본적으로 숫자 인덱스를 통한 접근밖에는 지원하지 않는다.

그러나 때로는 문자열을 키로 두고 값을 가져와야할 때가 발생하기도 한다. 이런 경우 C# 에서는 Dictionary 같은 클래스를 이용해 문제를 해결 해 볼 수 있다.

우선적으로 Dictionary 클래스는 다음과 같은 네임스페이스와 어셈블리를 사용한다.

네임스페이스:  System.Collections.Generic
어셈블리:  mscorlib(mscorlib.dll)

그럼 이 Dictionary 를 활용하려면 어떻게 해야할까? 우선 상단에 using 을 이용하여 네임스페이스를 추가해주는 것으로 시작한다. (해당 네임스페이스를 사용하기 위해서는 System 가 참조가 되어 있어야 하는 것은 기본.)

Dictionary 클래스에 대해 설명하고 있는 온라인 MSDN(http://msdn.microsoft.com/ko-kr/library/xfhwa508(v=VS.95).aspx) 의 예제 소스를 참고해 보면 다음과 같다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
//·Make·sure·this·class·is¬
//·within·the·C#·namespace.¬
public·class·OthelloCast·:·List<string>¬
{¬
····//·Use·a·dictionary·to·contain¬
····//·cast·names·(key)·and·actor·names·(value).¬
····public·Dictionary<string,·string>·OthelloDict·=¬
········new·Dictionary<string,·string>();¬
¬
····public·OthelloCast()¬
····{¬
········//·Add·data·to·the·dictionary.¬
········OthelloDict.Add("Bianca",·"Gretchen·Rivas");¬
········OthelloDict.Add("Brabantio",·"Carlos·Lacerda");¬
········OthelloDict.Add("Cassio",·"Steve·Masters");¬
········OthelloDict.Add("Clown",·"Michael·Ludwig");¬
········OthelloDict.Add("Desdemona",·"Catherine·Autier·Miconi");¬
········OthelloDict.Add("Duke·of·Venice",·"Ken·Circeo");¬
········OthelloDict.Add("Emilia",·"Eva·Valverde");¬
········OthelloDict.Add("Gratiano",·"Akos·Kozari");¬
········OthelloDict.Add("Iago",·"Darius·Stasevicius");¬
········OthelloDict.Add("Lodovico",·"Fernando·Souza");¬
········OthelloDict.Add("Montano",·"Jeff·Hay");¬
········OthelloDict.Add("Othello",·"Marco·Tanara");¬
········OthelloDict.Add("Roderigo",·"Pedro·Ruivo");¬
¬
········//·Populate·the·list·with·character·names.¬
········foreach·(KeyValuePair<string,·string>·kvp·in·OthelloDict)¬
········{¬
············this.Add(kvp.Key);¬
········}¬
····}¬
}
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
간단하게 값을 생성하고 입력하는 방법으로는 다음의 방법도 가능하다.
1
OthelloDict["MyFirstName"]·=·"Kim";
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

값의 출력으로는 다음과 같이 사용하면 된다.
1
Console.WriteLine(OthelloDict["MyFirstName"]);
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

기타 자세한 것은 위에 개제해 놓은 온라인 MSDN 링크를 참고하면 된다.

[기타 참고 자료]
C# - 파일을 읽어들여 구분자 문자열(String)을 키(Key)로 활용하여 리스트 생성하기 예제
반응형
Comments