박하의 나날

Dictionary<TKey, TValue>

프로그래밍/언어들
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
public enum type
    {
        Enemy,
    }
    
    Dictionary<type, List<enemy>> objectLists = new Dictionary<type, List<enemy>>();
    public void AddObject(type objType, enemy obj)
    {
        if (!objectLists.ContainsKey(objType))
        {
            objectLists[objType] = new List<enemy>();
        }
        if (!objectLists[objType].Contains(obj))
        {
            objectLists[objType].Add(obj);
        }
    }
    //특정타입에서 특정오브젝트 삭제
    public void RemoveObject(type objType, enemy obj)
    {
        if (objectLists[objType].Contains(obj))
        {
            objectLists[objType].Remove(obj);
        }
    }
 
cs



사용해 놓고도 잘 안다고 1도 할수는 없어서 자잘자잘하게 아는 설명적어보기.

리스트만 쓰거나 다른거 하나만쓰면 알겠는데 섞어쓰면 잘모르겠다....

Dictionary<TKey, TValue>

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

Add 지정한 키와 값을 가지는 요소를 추가

Remove 지정한 키를 가지는 요소를 제거

ContainsKey 특정키가 있는지 확인여부를 반환한다. 지정된키가 있으면 true, 아니면 false.




ex_1)

1
2
3
4
5
6
7
8
9
10
11
public class DictionaryEx{
    public static void Main(){
        IDictionary<stringstring> openWith = new IDictionary<stringstring>();
        if (!openWith.ContainsKey("ht"))
        {
            openWith.Add("ht""hypertrm.exe");
            Console.WriteLine("Value added for key = \"ht\": {0}"
                openWith["ht"]);
        }
    }
}
cs

ex_2)

using System; using System.Collections.Generic; public class FileFormatTable{ private Dictionary<string, string> openWith; public FileFormatTable(){ openWith = new Dictionary<string, string>(); //추가 openWith.Add("txt", "notepad.exe"); openWith.Add("bmp", "paint.exe"); openWith.Add("dib", "paint.exe"); openWith.Add("rtf", "wordpad.exe"); openWith.Add("odf", "wordpad.exe"); //이미 할당 된 키일 경우 try{ openWith.Add("txt", "windword.exe"); } catch{ Console.Writeline("an element with Key = \"txt\" already exists."); } //제거 openWith.Remove("odf"); } public void printTable(){ //탐색 foreach (KeyValuePair<string, string> d in openWith) Console.WriteLine("key = {0}, Value = {1}", d.Key, d.Value); } } class MainClass { public static vodi Main(string[] args) { FileFormatTable fileFormatTable = new FileFormatTable(); fileFormatTable.printTable(); } }



'프로그래밍 > 언어들' 카테고리의 다른 글

전방선언  (0) 2017.06.07
JavaScript)기초  (0) 2017.03.22