C#中利用Dictionary进行基于键值的元素快速查找

它的样式是Dictionary<TKey,TValue> Class,TKey表示字典中键的类型,TValue表示字典中值的类型,任何键都必须是唯一的。
以下是关于官方示例的引用

        static void Main(string[] args)
        {
            
            Dictionary<string, string> openWith = new Dictionary<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");

            // The Add method throws an exception if the new key is
            // already in the dictionary.
            try
            {
                openWith.Add("txt", "winword.exe");
            }
            catch (ArgumentException)
            {
                Console.WriteLine("An element with Key = \"txt\" already exists.");
            }
            Console.WriteLine("For key = \"rtf\", value = {0}.",openWith["rtf"]);
            
            if (!openWith.ContainsKey("ht"))//验证键值是否存在
            {
                openWith.Add("ht", "hypertrm.exe");
                Console.WriteLine("Value added for key = \"ht\": {0}", openWith["ht"]);
            }
            // 仅仅得到值的集合
            Dictionary<string, string>.ValueCollection valueColl =  openWith.Values;
           
            Console.WriteLine();
            foreach (string s in valueColl)
            {
                Console.WriteLine("Value = {0}", s);
            }
            //仅仅得到键的集合
            Dictionary<string, string>.KeyCollection keyColl = openWith.Keys;
            Console.WriteLine();
            foreach (string s in keyColl)
            {
                Console.WriteLine("Key = {0}", s);
            }           
        }

利用这个方法来解决字符串中某个字符出现的次数特别简单

    class Program
    {
        static Dictionary< string, int> dic = new Dictionary<string, int>();
        static void Main(string[] args)
        {
            int i = 6;
            while(i>0)
            {
                Insert(Console.ReadLine());
                i--;
            }
            foreach (var item in dic)
            {
                if (item.Value == 1)
                {
                    Console.WriteLine("第{0}值出现了一次", item.Key);
                }
                    
            }
        }
        public static void Insert(string c)
        {
            
            if (dic.ContainsKey(c))//ContainsKey包含则为真
                dic[c]++;
            else
                dic[c] = 1;
        }
    }
  • 3
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值