一、先来分别介绍一下ArrayList,Hashtable,List<T>,Dictionary<K,V>
1.ArrayList动态数组,保存值的时候比较好用
2.Hashtable以存储键值对的方式存储。value,和key
3.List<T> 和 Dictionary<K,V> 应该是泛型吧,可以保存实体类
二、各种集合的遍历方法演示
1.ArrayList
ArrayList list = new ArrayList();//for遍历for (int i = 0; i < list.Count; i++){ SE se = (SE)list[i]; Console.WriteLine(se.Name);}//foreach遍历foreach (Object obj in list){ SE se = (SE)list[i]; Console.WriteLine(se.Name);}
2.Hashtable
Hashtable list = new Hashtable();//Hashtable不能用索引访问,所以遍历一个Hashtable只能用foreache()方法//遍历Keyforeach (Object obj in list.Keys){ Console.WriteLine((string)obj);}//遍历Valueforeach (Object obj in list.Values){ SE se = (SE)obj; Console.WriteLine(se.Name);}//同时遍历,DictionaryEntry一个结构foreach (DictionaryEntry en in list){ Console.WriteLine(se.Keys); COnsole.WriteLine(((SE)en.Value).Name);}
3.List<T>
//for遍历for (int i = 0; i < list.Count; i++){ //遍历时不需要类型转换 Console.WriteLine(list[i]);}//foreach遍历foreach (SE obj in list){ //遍历时不需要类型转换 Console.WriteLine(obj);}
4.Dictionary<K,V>
//遍历Valuesforeach (SE se in list.Values){ //遍历时不需要类型转换 Console.WriteLine(se);}//同时遍历foreach (KeyValuePair<string, SE> en in list){ Console.WriteLine(en.Key); Console.WriteLine(en.Value.Name);}//KeyValuePair<TKey,TValue>是一个泛型结构