Dictionary的用法

Dictionary比HashTable更好用

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DictionaryUsage
{
    internal class Program
    {
        private static void Main(string[] args)
        {
            var dic = new Dictionary<int, string> {{1, "hang"}, {2, "hong"}, {3, "ximi"}};
            //foreach (var temp in dic)
            //{
            //    Console.WriteLine("key: {0},value: {1}",temp.Key,temp.Value);
            //}
            //Console.WriteLine(dic);
            //var a = dic.Where(var => var.Key == 2).GetEnumerator().Current.Value;
            //Console.WriteLine(a);

            //取值
            Console.WriteLine(dic[1]);

            //添加元素
            dic.Add(4, "notepad.exe");
            dic.Add(5, "paint.exe");
            dic.Add(6, "paint.exe");
            dic.Add(7, "wordpad.exe");

            //更改值
            dic[1] = "nihang1234";

            //遍历字典
            foreach (var temp in dic)
            {
                Console.WriteLine("key: {0},value: {1}", temp.Key, temp.Value);
            }

            //遍历键
            foreach (var temp in dic.Keys)
            {
                Console.WriteLine(temp);
            }

            //遍历值
            foreach (var temp in dic.Values)
            {
                Console.WriteLine(temp);
            }

            Console.ReadKey();
        }
    }
}

posted on 2017-09-23 09:55  五月槐花  阅读(83)  评论(0编辑  收藏  举报

导航