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);

            }
            
        }
}
}

}


  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值