对于.net Framework中内置的几种集合类,foreach是一种很方便的遍历方式:
非泛型&弱类型的Collections(ArrayList,Queue,Stack):ArrayList al = new ArrayList(); al.Add("hello"); al.Add(1); [color=#00ff !important]foreach(object obj in al) { Console.WriteLine(obj.ToString()); } |
ArrayList al = new ArrayList(); al.Add("hello"); al.Add("world"); [color=#00ff !important]foreach(string s in al) { Console.WriteLine(s); } |
Hashtable ht = new Hashtable(); ht.Add(1, "Hello"); ht.Add(2, "World"); [color=#00ff !important]foreach (DictionaryEntry de in ht) { Console.WriteLine(de.Value); } |
NameValueCollection nvc = new NameValueCollection(); nvc.Add("a", "Hello"); nvc.Add("a", "World"); nvc.Add("b", "!"); [color=#00ff !important]foreach (string key in nvc.AllKeys) { foreach (string value in nvc.GetValues(key)) { Console.WriteLine(value); } } |
Dictionary<int, string> dic = new Dictionary<int, string>(); dic.Add(1, "Hello"); dic.Add(2, "World"); [color=#00ff !important]foreach(KeyValuePair<int,string> pair in dic) { Console.WriteLine(pair.Value); } |
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/) | 黑马程序员IT技术论坛 X3.2 |