工作上的需要, 我寫程式碼必須做配對 key, and Value
但是希望不要限制 type, 可以自由度高一點
C++的話 會想到std::map這個方式
但是我們今天程式碼是透過C#撰寫
那就要找另外的方式, 上網找看看吧! 找到如下…
1 2 3 |
<a href="http://stackoverflow.com/questions/21183414/what-is-c-sharp-equivalent-of-map-in-c" target="_blank" rel="noopener noreferrer">What is C# equivalent of <map> in C++?</a> The equivalent would be class <strong>SortedDictionary<TKey, TValue></strong> in the <strong>System.Collections.Generic </strong>namespace. If you don't care about the order the class <strong>Dictionary<TKey, TValue></strong> in the <strong>System.Collections.Generic </strong>namespace would probably be sufficient. |
既然有兩個class可以使用, 就選SortedDictionary吧~
MSDN有完整的說明與介紹, 如何使用SortedDictionary來開發~
初始與放進去:
1 2 3 4 5 6 7 8 9 10 11 |
// Create a new sorted dictionary of strings, with string // keys. SortedDictionary<string, string> openWith = new SortedDictionary<string, string>(); // 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則會新增進去:
1 2 3 |
// 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被放進去:
1 2 3 4 5 6 7 8 |
// When you use foreach to enumerate dictionary elements, // the elements are retrieved as KeyValuePair objects. Console.WriteLine(); foreach( KeyValuePair<string, string> kvp in openWith ) { Console.WriteLine("Key = {0}, Value = {1}", kvp.Key, kvp.Value); } |
大概就這樣~