C#/수업내용

2020.04.21. 수업내용 - Dictionary 개요

dev_sr 2020. 4. 21. 16:06

 

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
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
 
namespace Study_013_1
{
    class App
    {
        public App()
        {
            //컬렉션 중의 하나,  각각의 요소들이 키와 값으로 이뤄진다.
            //아무튼 엄청 빠르다
 
            //타입                   Dictionary객체    새로운 Dictionary 객체가 만들어진다
            Dictionary<stringstring> openWith = new Dictionary<stringstring>();
 
 
            //반드시 키와 값 쌍으로 넣어야하며
            //중복된 키의 값은 허용하지 않는다. (중복되면 에러)
            //값은 중복되어도 됨
 
            openWith.Add("txt""notepad.exe");
            openWith.Add("bmp""paint.exe");
            openWith.Add("dib""paint.exe");
            openWith.Add("rtf""wordpad.exe");
 
            //같은 키 txt ==> 에러
            openWith.Add("txt""winword.exe");
 
            //rtf키의 값 : "wordpad.exe"가 출력
            Console.WriteLine("For key = \"rtf\", value = {0}.", openWith["rtf"]);
 
            //키를 찾아서 값을 변화시킬 수도 있다! 출력값 : "winword.exe"
            openWith["rtf"= "winword.exe";
            Console.WriteLine("For key = \"rtf\", value = {0}.", openWith["rtf"]);
 
            //만약에 기존에 없던 새로운 키값이라면 요소에 추가할 수 있다.
            openWith["doc"= "winword.exe";
 
 
            //인덱서가 키워드를 배열처럼 사용하게 해준다.
            Console.WriteLine("For key = \"tif\", value = {0}.", openWith["tif"]);
 
            //ht라는 키 값이 없다면 딕션너리에 추가하고 출력한다.
            if (!openWith.ContainsKey("ht"))
            {
                openWith.Add("ht""hypertrm.exe");
                Console.WriteLine("Value added for key = \"ht\": {0}", openWith["ht"]);
            }
 
 
            //foreach문을 실행하려면 KeyValuePair라는 오브젝트(객체)를 사용해야한다.
            //딕셔너리에 들어있는 값은 오브젝트이다
            foreach (KeyValuePair<stringstring> kvp in openWith)
            { 
                                                          //키 접근, //값 접근
                Console.WriteLine("Key = {0}, Value = {1}"kvp.Key, kvp.Value);
            }
 
            //키값을 넣으면 지워진다
            openWith.Remove("doc");
 
 
 
        }
 
    }
}
 
 

 

기타

 

1. count : 요소의 값 개수 출력(키, 값 쌍의 수)

2. Key : 모든 Key값 컬렉션에 접근한다(가져온다)

3. Value : 모든 Value값 컬렉션에 접근한다(가져온다)

4. Clear: 딕셔너리의 모든 키와 값을 지운다.

 

 

출처: https://docs.microsoft.com/ko-kr/dotnet/api/system.collections.generic.dictionary-2?view=netframework-4.8