C# Dictionary用法汇总(定义、遍历、排序)

1、Dictionary 定义
Dictionary<string, double> dic = new Dictionary<string, double>();
dic.Add("语文", 98.5); 
        dic["数学"] = 97;
       
Dictionary<string, double> dic 
                     = new Dictionary<string, double>() { {"语文",95},{"数学",98.5} };
         
2、通过KeyValuePair 遍历元素
foreach(KeyValuePair<int,string> kv in dic)
{
   Console.WriteLine("Key = {0}, Value = {1}",kv.Key, kv.Value);
}

3、Foreach遍历 字典
            Dictionary<int, string>.KeyCollection keyCol = dic.Keys;
            foreach (int key in keyCol)
            {
                Console.WriteLine("Key = {0}", key);
            }
4、For 遍历字典
    for (int i = 0; i < dic.Count; i++)
            {
                KeyValuePair<string, double> kv = dic.ElementAt(i);
                Console.WriteLine("Key = {0}, Value = {1}",kv.Key, kv.Value);  
            }
5、仅 遍历值 Key属性
            Dictionary<int, string>.KeyCollection keyCol = dic.Keys;
            foreach (int key in keyCol)
            {
                Console.WriteLine("Key = {0}", key);
            }
6、仅遍历值 Valus属性
            Dictionary<int, string>.ValueCollection valueCol = dic.Values;
            foreach (string value in valueCol)
            {
                Console.WriteLine("Value = {0}", value);
            }

7、通过Remove方法移除指定的键值           
            if (dic.ContainsKey("语文"))
            {
                Console.WriteLine("移除键:Key:{0},Value:{1}", "语文", dic["语文"]);
                dic.Remove("语文");
            }
            else
            {
                Console.WriteLine("不存在 Key : 1");
            }
8、字典 排序    
dic = dic .OrderByDescending(r => r.Value).ToDictionary(r => r.Key, r => r.Value);
  • 3
    点赞
  • 14
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值