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
原创粉丝点击