对于.net Framework中内置的几种集合类,foreach是一种很方便的遍历方式:
非泛型&弱类型的Collections(ArrayList,Queue,Stack):
使用object:
ArrayList al = new ArrayList();
al.Add("hello");
al.Add(1);
foreach(object obj in al)
{
Console.WriteLine(obj.ToString());
}
如果确定ArrayList中的类型的话,也可以用这个类型代理,会自动强转,但若转换不成功,抛出InvalidCastException。
ArrayList al = new ArrayList();
al.Add("hello");
al.Add("world");
foreach(string s in al)
{
Console.WriteLine(s);
}
强类型的Collections(StringCollection和BitArray),可分别使用string和bool而无需强转。
非泛型的Dictionaris(Hashtable, SortedList,StringDictionary等):
使用DictionaryEntry:
Hashtable ht = new Hashtable();
ht.Add(1, "Hello");
ht.Add(2, "World");
foreach (DictionaryEntry de in ht)
{
Console.WriteLine(de.Value);
}
特殊的Dictionary(NameValueCollection):
不能直接对NameValueCollection进行foreach遍历,需要两级:
NameValueCollection nvc = new NameValueCollection();
nvc.Add("a", "Hello");
nvc.Add("a", "World");
nvc.Add("b", "!");
foreach (string key in nvc.AllKeys)
{
foreach (string value in nvc.GetValues(key))
{
Console.WriteLine(value);
}
}
泛型Collections
List
Dictionary
Dictionary
dic.Add(1, "Hello");
dic.Add(2, "World");
foreach(KeyValuePair
{
Console.WriteLine(pair.Value);
}
注意 : 在foreach过程中,集合类长度的改变会导致错误,因此foreach的循环体中不要有对集合类的增减操作。而Dictionary
[整理自网络]
分类目录
- arch/management (17)
- computer (38)
- DB/ES (125)
- java/j2ee (305)
- lnmp (236)
- mac/iphone/ipad/android (11)
- os/software (75)
- other (516)
- python (7)
- redis/memcached/mongo (31)
- sitebuild (143)
友情链接
收藏链接