黑马程序员技术交流社区

标题: C#中Collection和Dictionary的foreach遍历方式 [打印本页]

作者: 柏森仁    时间: 2012-8-10 14:47
标题: C#中Collection和Dictionary的foreach遍历方式

对于.net Framework中内置的几种集合类,foreach是一种很方便的遍历方式:

非泛型&弱类型的Collections(ArrayList,Queue,Stack):
使用object:
[size=1em]?

ArrayList al = new ArrayList();
al.Add("hello");
al.Add(1);
[color=#00ff !important]foreach(object obj in al)
{
    Console.WriteLine(obj.ToString());
}

如果确定ArrayList中的类型的话,也可以用这个类型代理,会自动强转,但若转换不成功,抛出InvalidCastException
[size=1em]?

ArrayList al = new ArrayList();
al.Add("hello");
al.Add("world");
[color=#00ff !important]foreach(string s in al)
{
    Console.WriteLine(s);
}

强类型的Collections(StringCollectionBitArray),可分别使用string和bool而无需强转。
非泛型的Dictionaris(Hashtable, SortedList,StringDictionary等):
使用DictionaryEntry:
[size=1em]?

Hashtable ht = new Hashtable();
ht.Add(1, "Hello");
ht.Add(2, "World");
[color=#00ff !important]foreach (DictionaryEntry de in ht)
{
    Console.WriteLine(de.Value);
}

特殊的Dictionary(NameValueCollection):
不能直接对NameValueCollection进行foreach遍历,需要两级:
[size=1em]?

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);
    }
}

泛型Collections
List<T>,Queue<T>,Stack<T>: 这个好说,foreach T 就可以了。
Dictionary<Tkey,TValue>和SortedList<Tkey,TValue> 要使用KeyValuePair<Tkey,TValue>:
[size=1em]?

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);
}

注意 : 在foreach过程中,集合类长度的改变会导致错误,因此foreach的循环体中不要有对集合类的增减操作。而Dictionary<Tkey,TValue>是非线程安全的,多线程时对其使用foreach可能会引起错误,多线程时推荐使用非泛型的Hashtable(或者自己lock..)。

作者: 许庭洲    时间: 2012-8-10 15:08
值得学习!




欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/) 黑马程序员IT技术论坛 X3.2