1. 程式人生 > 實用技巧 >C#中Collection和Dictionary的foreach遍歷方式

C#中Collection和Dictionary的foreach遍歷方式

原文:http://blog.sojingle.net/programming/csharp/csharp-collections-dictionaries-using-foreach

對於.net Framework中內建的幾種集合類,foreach是一種很方便的遍歷方式:

1.非泛型&弱型別的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);
}

2.強型別的Collections(StringCollectionBitArray),可分別使用string和bool而無需強轉。

3.非泛型的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);
    }
}

4.泛型Collections

List<T>,Queue<T>,Stack<T>: 這個好說,foreach T 就可以了。

5.Dictionary<Tkey,TValue>和SortedList<Tkey,TValue> 要使用KeyValuePair<Tkey,TValue>:

Dictionary<int, string> dic = new Dictionary<int, string>();
dic.Add(1, "Hello");
dic.Add(2, "World");
foreach(KeyValuePair<int,string> pair in dic)
{
    Console.WriteLine(pair.Value);
}

注意 : 在foreach過程中,集合類長度的改變會導致錯誤,因此foreach的迴圈體中不要有對集合類的增減操作。而Dictionary<Tkey,TValue>是非執行緒安全的,多執行緒時對其使用foreach可能會引起錯誤,多執行緒時推薦使用非泛型的Hashtable(或者自己lock..)。