C#for和foreach的区别-----dictionary遍历的方式
来源:互联网 发布:java什么类不能被继承 编辑:程序博客网 时间:2024/05/15 11:40
一、遍历方式
dictionary遍历的方式有两种:一种是通过foreach,一种是通过for来实现遍历。
Dictionary<string,string> list=new Dictionary<string,string>;foreach(var item in list){ Console.WriteLine(item.Key+item.Value);}//KeyValuePair<T,K>foreach(KeyValuePair<string,string> kv in list){ Console.WriteLine(kv.Key+kv.Value);}//通过键的集合取foreach(string key in list.Keys){ Console.WriteLine(key+list[key]);}//for循环遍历List<string> test=new List<string>(list.Keys);for(int i=0;i<list.Count;i++){ Console.WriteLine(test[i]+list[test[i]]);}
二、注意事项:
对于基本类型的集合,foreach可以任意修改集合中元素。对于引用类型的集合(如studentEntity),不能进行元素的添加或删除等改变引用的操作。否则会报错:Collection Was modified;enumeration Operation may not execute,当用foreach遍历Collection时,如果Collection有Add或者Remove操作或者给item某个属性赋值都会有这个错误。但可以改变元素(对象)的属性(如改变studentEntity的name属性为张三)。
三、移除元素
上文已经提到了移除dictionary(Collection)中的元素,不能使用foreach,只能使用for来实现。
for(int i=0;i<list.count;i++){ if(list[i]) { list.RemoveAt(i); }}如果这样循环,肯定不对,{A B C D E F G H}假设当前遍历到D(i=3),移除,接着遍历i=4(F),此时跳过了E。
我们使用倒序遍历,这个问题就能迎刃而解啦。
for(int i=list.Count-1;i>=0;i--){ if(list[i]) { list.RemoveAt(i); }}
项目中用到的真实代码:
public static OperationResult CheckAddOrUpdateMetaFields(ObjectData objectData) { OperationResult result = new OperationResult(); result.Code = 200; Dictionary<string, Data> dictionaryFields = objectData.MetaFields; //任务所有的字段 List<string> allowedList = TaskManageConst.GetAllowedMetaFieldsList(); for (int i = 0; i < dictionaryFields.Count; i++) { if (!allowedList.Contains(dictionaryFields.ElementAt(i).Key))//key不在allowedList,移除 { dictionaryFields.Remove(dictionaryFields.ElementAt(i).Key); i--; } } return result; }
阅读全文
1 0
- C#for和foreach的区别-----dictionary遍历的方式
- C#中Collection和Dictionary的foreach遍历方式
- 数组遍历for与foreach的区别
- foreach和for的区别
- for和foreach的区别
- foreach和for的区别
- for和foreach的区别
- for 和 foreach 的区别
- for 和foreach的区别
- foreach和for的区别
- Iterator,for,forEach的遍历和效率
- JAVA for和foreach 遍历的效率
- map和foreach遍历的区别
- [Dotnet][C#]Dictionary的foreach使用KeyValuePair
- for,foreach,iterator的用法和区别
- for,foreach,iterator的用法和区别
- for,foreach,iterator的用法和区别
- for,foreach,iterator的用法和区别
- TCP/IP协议栈和 ISO模型
- 使用前序和中序遍历重构二叉树
- Longest Consecutive Sequence
- 调试i2s/pcm笔记
- Vue.js 学习10 Element基于Vue2.0的组件库
- C#for和foreach的区别-----dictionary遍历的方式
- VIM学习笔记
- 像大牛一样写代码: 31个Android 开发者工具
- Text设置
- 华为编程题---进制转换
- Python 编码规范 BY Google
- GC系列:如何优化引用计数算法(1)
- 7zip和winrar命令行备份
- C++中vector的用法