一般地Dictionary是按照元素的添加顺序输出的,这和HashTable不同。

Dictionary<int, string> dictionary = new Dictionary<int, string>();

dictionary.Add(1, "xiaowang");

dictionary.Add(21, "dsd");

dictionary.Add(33, "dsfdfd");

dictionary.Add(4, "liusang");

foreach (KeyValuePair<int, string> kvp in dictionary)

{

    Console.WriteLine("key={0},value={1}", kvp.Key, kvp.Value);

}

foreach (int j in dictionary.Keys)

{

    Console.WriteLine("key={0},value={1}", j, dictionary[j]);

}

Hashtable table = new Hashtable();

table.Add(1, "wang gang");

table.Add(21, "xiao li");

table.Add(33, "xiao fan");

table.Add(4, "fff");

foreach (int i in table.Keys)

{

    Console.WriteLine("key={0},value={1}", i, table[i]);

}

foreach (string str in table.Values)

{

    Console.WriteLine("value={0}", str);

}

System.Collections.IDictionaryEnumerator d = table.GetEnumerator();

while (d.MoveNext())

{

    System.Console.WriteLine("key={0},value={1}",d.Entry.Key,d.Entry.Value);

}

foreach (DictionaryEntry entry in table)

{

    Console.WriteLine("key={0},value={1}", entry.Key, entry.Value);

}

Console.ReadLine();

 

输出结果:

key=1,value=xiaowang

key=21,value=dsd

key=33,value=dsfdfd

key=4,value=liusang

key=1,value=xiaowang

key=21,value=dsd

key=33,value=dsfdfd

key=4,value=liusang

key=21,value=xiao li

key=4,value=fff

key=1,value=wang gang

key=33,value=xiao fan

value=xiao li

value=fff

value=wang gang

value=xiao fan

key=21,value=xiao li

key=4,value=fff

key=1,value=wang gang

key=33,value=xiao fan

key=21,value=xiao li

key=4,value=fff

key=1,value=wang gang

key=33,value=xiao fan