C# 用SortedDictionary Class 取代 C++的std::map

工作上的需要, 我寫程式碼必須做配對 key, and Value
但是希望不要限制 type, 可以自由度高一點

C++的話 會想到std::map這個方式
但是我們今天程式碼是透過C#撰寫

那就要找另外的方式, 上網找看看吧! 找到如下…

What is C# equivalent of  in C++?
The equivalent would be class SortedDictionary in the System.Collections.Generic namespace.
If you don't care about the order the class Dictionary in the System.Collections.Generic namespace would probably be sufficient.

既然有兩個class可以使用, 就選SortedDictionary吧~
MSDN有完整的說明與介紹, 如何使用SortedDictionary來開發~

初始與放進去:

        // Create a new sorted dictionary of strings, with string
        // keys.
        SortedDictionary openWith = 
            new SortedDictionary();

        // Add some elements to the dictionary. There are no 
        // duplicate keys, but some of the values are duplicates.
        openWith.Add("txt", "notepad.exe");
        openWith.Add("bmp", "paint.exe");
        openWith.Add("dib", "paint.exe");
        openWith.Add("rtf", "wordpad.exe");

修改, 若不存在這個key則會新增進去:

// If a key does not exist, setting the indexer for that key
        // adds a new key/value pair.
        openWith["doc"] = "winword.exe";

可以用這段KeyValuePair來檢驗是否正確的key & value被放進去:

        // When you use foreach to enumerate dictionary elements,
        // the elements are retrieved as KeyValuePair objects.
        Console.WriteLine();
        foreach( KeyValuePair kvp in openWith )
        {
            Console.WriteLine("Key = {0}, Value = {1}", 
                kvp.Key, kvp.Value);
        }

大概就這樣~

發表迴響