C#中遍历各类数据集合的方法总结:
1.枚举类型
//遍历枚举类型Sample的各个枚举名称 foreach (string sp in Enum.GetNames(typeof(Sample))) { ary.Add(sp); } //遍历枚举类型Sample的各个枚举值 foreach (string sp in Enum.GetValues(typeof(Sample))) { ary.Add(sp); } |
2.遍历ArrayList(Queue、Stack)
这里以string为例,当然ArrayList中的元素可以是任何数据类型,遍历时须确认ArrayList中的元素都是同一数据类型。
//遍历元素为string类型的队列 foreach (string text in arraylist) { ary.Add(text); } |
此外遍历Queue队列和Stack堆栈的方式与ArrayList基本相同, 都可以使用foreach来循环遍历,只不过一个是先进先出另一个是先进后出罢了。
3.Winform窗体中的控件
//遍历寻找主窗体中的控件,并将符合条件的控件从窗体上去除 foreach (Control ctl in this.Controls) { //获取并判断控件类型或控件名称 if (ctl.GetType().Name.Equals("ListBox") || ctl.Name.Equals("listBox1")) this.Controls.Remove(ctl); } |
4.HashTable哈希表
DictionaryEntry类需要引用System.Collections //遍历完整哈希表中的键和值 foreach (DictionaryEntry item in hashTable) { ary.Add("哈希键:"+item.Key+",哈希值:"+item.Value.ToString()); } |
此外还可以单独遍历哈希表中的键或值。