C# 字典集合

字典集合

using System;
using System.Collections.Generic;

namespace 字典集合
{
    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[1] = "新来的";
                foreach(var item in dic.Keys)
            {
                Console.WriteLine("{0}--{1}", item, dic[item]);
            }
            Console.ReadKey();
        }
    }
}

一个字典使用方法。

  • 字典命名空间:
System.Collections.Generic;
  • 直接遍历键值对的方法:

  • foreach(KeyValuePai<..,..(键值对数据类型)> kv in 集合)
    {
    	//kv即代表键,也代表值
    	console.writeLIne("{0}---{1}",kv.Key,kv.Value);
    }
    cosnole.ReadKey();
    //这样遍历更为简洁和优雅
    
  • [外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-ZkWs2aW6-1632129597810)(C:\Users\33640\AppData\Roaming\Typora\typora-user-images\image-20201215103405500.png)]

一个变相的遍历集合的方法

  • 一道遍历键值对的题
using System;
using System.Collections.Generic;

namespace 字典集合
{
    class Program
    {
        static void Main(string[] args)
        {
            //键值对集合是根据键去找值
            //字符--》出现的次数
            string str = "Welcom to China";
            Dictionary<char, int> dic = new Dictionary<char, int>();

            for (int i = 0; i < str.Length; i++)
            {
               if(str[i] == ' ')
                {
                    continue;
                }
                //如果dic已经包含了当前循环的这个键
                if(dic.ContainsKey(str[i]))
                {
                    dic[str[i]]++;
                }
                else //这个字符在集合当中是第一次出现
                {
                    dic[str[i]] = 1;

                }
                foreach (KeyValuePair<char , int> kv in dic)
                {
                    Console.WriteLine("字母{0}出现了{1}次",kv.Key,kv.Value);

                }
                
            }
    }
    }
}

1}次",kv.Key,kv.Value);

            }
            
        }
}
}

}


猜你喜欢

转载自blog.csdn.net/learner_syj/article/details/120393261