bloggerads

2015年12月31日 星期四

C# : algorithm "Dictionary" sample code

The following sample code was searched from internet, It's a good example to show how C++ map work on C# as Dictionary


// Algorithm map
namespace Map
{
    class Program
    {
        static void Main(string[] args)
        {
            // Use Dictionary as a map.
            var map = new Dictionary<string, string>();

            // ... Add some keys and values.
            map.Add("cat", "orange");
            map.Add("dog", "brown");

            // ... Loop over the map.
            foreach (var pair in map)
            {
                string key = pair.Key;
                string value = pair.Value;
                Console.WriteLine(key + "/" + value);
            }

            // ... Get value at a known key.
            string result = map["cat"];
            Console.WriteLine(result);

            // ... Use TryGetValue to safely look up a value in the map.
            string mapValue;
            if (map.TryGetValue("dog", out mapValue))
            {
                Console.WriteLine(mapValue);
            }
        }
    }
}

沒有留言:

張貼留言