2013/12/23

C#.Net Dictionary

Dictionary中文意思是字典,字典目錄的頁碼可以找到資料
一個頁碼對上一筆資料,而不會一個頁碼對上多筆資料



程式碼:
using System;
using System.Collections.Generic;

namespace MyDictionary
{
    class Program
    {
        struct Book
        {
            public String name;
            public int price;
        };

        static void Main(string[] args)
        {

            Dictionary<int, Book> dictionary = new Dictionary<int, Book>()
            {
                {1,new Book { name = "C++",  price = 1000 } },
                {2,new Book { name = "Java",  price = 500 } },
                {3,new Book { name = "C#",  price = 700 } }
            };


            try
            {
                Console.WriteLine(dictionary[1].name);
                Console.WriteLine(dictionary[4].name);
            }
            catch (KeyNotFoundException ex)
            {
                Console.WriteLine("No found.");
            }

            Console.Read();

        }
    }
}




執行結果:


參考資料:
http://msdn.microsoft.com/zh-tw/library/xfhwa508(v=vs.110).aspx
http://msdn.microsoft.com/zh-tw/library/bb531208(v=vs.110).aspx
http://stackoverflow.com/questions/14834532/discrepancies-between-output-of-dictionaryint-string-and-queuekeyvaluepairi