C# Dictionary
来源:互联网 发布:js 移动端 上传照片 编辑:程序博客网 时间:2024/05/23 00:03
主要是很多不留意的地方会出异常,相对java的HashMap没法比,如果需要只能自己扩展些方法。
例如:使用索引获取值的时候,如果key为空,会有KeyNotFoundException
如果Add已经存在的key,还会抛异常。
这里记录几种遍历的方法:
Dictionary<string, int> list = new Dictionary<string, int>(); list.Add("d", 1); //3.0以上版本 foreach (var item in list) { Console.WriteLine(item.Key + item.Value); } //KeyValuePair<T,K> foreach (KeyValuePair<string, int> kv in list) { Console.WriteLine(kv.Key + kv.Value); } //通过键的集合取 foreach (string key in list.Keys) { Console.WriteLine(key + list[key]); } //直接取值 foreach (int val in list.Values) { Console.WriteLine(val); } //非要采用for的方法也可 List<string> test = new List<string>(list.Keys); for (int i = 0; i < list.Count; i++) { Console.WriteLine(test[i] + list[test[i]]); }
更新key最好用
dict["xxxx"] = "xxxxxxxxx";
这样就不会因为存在而发生异常,只会addOrUpdate 这样就不会因为存在而发生异常,只会addOrUpdate
如果非得用Add,那就先判断再添加
if (dict.ContainsKey(2) == false) dict.Add("xxxxxxxxx", "xxxxxxx");
0 0
- C# Dictionary
- C# Dictionary
- C# Dictionary
- C# Dictionary
- C# Dictionary
- C# Dictionary
- C# Dictionary
- C# Dictionary
- C# Dictionary
- C# Dictionary
- C# Dictionary
- C# Dictionary
- C# Dictionary
- C# Dictionary 泛型类 记录
- c# Dictionary集合
- C#中的Dictionary简介
- C# Dictionary学习
- C# Dictionary 终极使用方法
- poj 2774 最长公共子串(后缀数组)
- Linux文件压缩
- Git 使用备忘录
- 关于spl_autoload_register()
- Bias-Variance Tradeoff(权衡偏差与方差)
- C# Dictionary
- Python Scrapy安装(python 版本手动更新)
- python 发送邮件
- Python字符串笔记
- POJ 2010(二分最大化中间值)
- 总结—Github上传项目完整步骤(基本)
- localhost能访问,127.0.0.1却不能访问的原因
- Linux 统计文件行数,字节数。
- 将json中的数据加载到table和ul中