2011年6月2日木曜日

C# hashtable 列挙

  1. using System;  
  2. using System.Collections;  
  3.   
  4. public class test {  
  5.   static void Main() {  
  6.     Hashtable ht = new Hashtable();  
  7.   
  8.     // データの追加その1  
  9.     ht["japan"] = "日本";  
  10.     ht["america"] = "アメリカ";  
  11.   
  12.     // データの追加その2  
  13.     ht.Add("china""中国");  
  14.     ht.Add("india""インド");  
  15.   
  16.     // データの取得  
  17.     string val = (string)ht["japan"];  
  18.     Console.WriteLine(val); // 出力:日本  
  19.   
  20.     // キー項目の列挙  
  21.     foreach (string key in ht.Keys) {  
  22.       Console.WriteLine("{0} : {1}", key, ht[key]);  
  23.     }  
  24.     // 出力例:  
  25.     // india : インド  
  26.     // japan : 日本  
  27.     // america : アメリカ  
  28.     // china : 中国  
  29.   
  30.     // 値項目の列挙  
  31.     foreach (string value in ht.Values) {  
  32.       Console.WriteLine(value);  
  33.     }  
  34.     // 出力例:  
  35.     // インド  
  36.     // 日本  
  37.     // アメリカ  
  38.     // 中国  
  39.   
  40.     // キーの存在チェック  
  41.     if (!ht.ContainsKey("france")) {  
  42.       ht["france"] = "フランス";  
  43.     }  
  44.   
  45.     // 値の存在チェック  
  46.     Console.WriteLine(ht.ContainsValue("日本")); // 出力例:True  
  47.   
  48.     // エントリ(キーと値)の列挙  
  49.     foreach (DictionaryEntry de in ht) {  
  50.       Console.WriteLine("{0} : {1}", de.Key, de.Value);  
  51.     }  
  52.     // 出力例:  
  53.     // india : インド  
  54.     // japan : 日本  
  55.     // france : フランス  
  56.     // america : アメリカ  
  57.     // china : 中国  
  58.   }  
  59. }  

0 件のコメント:

コメントを投稿