Using system; using system. collections. generic; public class example {public static void main () {// 1. Create a generic hash table and add the element dictionary <string, string> Oscar = new dictionary <string, string> (); Oscar. add ("Hali? Berry "," the dance of death "); Oscar. Add (" Judy? Dan Qi "," Join Hands "); Oscar. Add (" Nicole? Kidman "," Moulin Rouge "); Oscar. Add (" Jennifer? Conway "," beautiful soul "); Oscar. Add (" renni? Qi weige "," BJ single Diary "); // II. Delete the element Oscar. Remove (" Jennifer? Conway "); // 3. If no element exists, add the element if (! Oscar. containskey ("? Spark ") Oscar. Add (" sissy? Sparks "," "); // 4. Console of apparent capacity and number of elements. writeline ("number of elements: {0}", Oscar. count); // 5. traverse the set console. writeline ("74 Oscar best actress and movie:"); foreach (keyvaluepair <string, string> kVp in Oscar) {console. writeline ("Name: {0}, movie: {1}", kVp. key, kVp. value);} // 6. Obtain the set of keys in the hash table <string, string>. keycollection keycoll = Oscar. keys; // The console that traverses the key set. writeline ("Best Actress:"); foreach (string s in keycoll) {console. writeline (S) ;}// 7. Set of hash table values: dictionary <string, string>. valuecollection valuecoll = Oscar. values; // The set console that traverses values. writeline ("Best Actress movie:"); foreach (string s in valuecoll) {console. writeline (s);} // 8. Use the trygetvalue method to obtain the string slove = string. empty; If (Oscar. trygetvalue ("Judy? Dan Qi ", out slove) console. writeline (" My favorite Judy? Dan Qi's movie {0} ", slove); else console. writeline (" no Judy found? Danqi movie "); // IX. Clear the hash table Oscar. Clear (); console. Readline ();}}
C # dictionary Traversal