码迷,mamicode.com
首页 > Windows程序 > 详细

C#的Dictionary字典

时间:2015-05-26 21:26:14      阅读:238      评论:0      收藏:0      [点我收藏+]

标签:c#   dictionary   字典   哈希   

Dictionary

Dictionary可以取代Hashtable了;
有一种新的遍历方式

foreach(KeyValuePair <int,string> kv in dic){}

dictionary练习

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

namespace Dictionary字典
{
    class Program
    {
        static void Main(string[] args)
        {
            Dictionary<int, string> dic = new Dictionary<int, string>();
            dic.Add(1, "荆轲");
            dic.Add(2, "聂政");
            dic.Add(3, "专诸");
            dic.Add(4, "要离");
            foreach (int item in dic.Keys)
            {
                Console.WriteLine("{0}对应的值为{1}",item,dic[item]);
            }
            foreach(KeyValuePair<int,string> pair in dic)
            {
                Console.WriteLine("{0}对应的值为{1}",pair.Key,pair.Value);
            }
            Console.ReadKey();
        }
    }
}

用Dictionary检测字符出现次数

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

namespace Dictionary检测字母出现次数
{
    class Program
    {
        static void Main(string[] args)
        {
            //检测字符串"Welcome To China"里面每个字符出现的次数;
            Dictionary<char, int> dic = new Dictionary<char, int>();
            string str = "Welcome To China";
            for (int i = 0; i < str.Length; i++)
            {
                if (str[i]==‘ ‘)
                {
                    continue;
                }
                if (dic.ContainsKey((str.ToLower())[i]))
                {
                    dic[(str.ToLower())[i]]++;
                }
                else
                {
                    dic[(str.ToLower())[i]] = 1;
                }
            }
            foreach (KeyValuePair<char,int> item in dic)
            {
                Console.WriteLine("{0}出现过{1}次",item.Key,item.Value);
            }
            Console.ReadKey();

        }
    }
}

C#的Dictionary字典

标签:c#   dictionary   字典   哈希   

原文地址:http://blog.csdn.net/zhzz2012/article/details/46012139

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!