最近、C# を書くようになって、PHP の連想配列のように、配列のキーに、文字列を指定したいと思い調べると、Dictionary 型というものがあったので、使ってみました。
・PHP で連想配列を書いた場合
<?php
sample();
function sample()
{
$items['Apple'] = 'りんご';
$items['Banana'] = 'バナナ';
$items['Grape'] = 'ぶどう';
$items['Orange'] = 'オレンジ';
foreach($items as $k => $v)
{
echo($k . ':' .$v);
}
}
・C# の Dictionary 型で連想配列っぽい使い方で書いた場合
void Sample()
{
Dictionary<string, string> items = new Dictionary<string, string>();
items.Add("Apple", "りんご");
items.Add("Banana", "バナナ");
items.Add("Grape", "ぶどう");
items.Add("Orange", "オレンジ");
foreach (var item in items)
{
Debug.WriteLine(item.Key + " : " + item.Value);
}
}
これで、C#で、連想配列的に書くことができそうです。Dictionary<string, string> この <> の部分で、キーと値のペアで型を指定してます。例では、値の部分に string(文字列)を指定していますが、クラスを書くこともできるので、文字列以外にも、色々登録できそうです。
他にも、PHPの連想配列操作で、必要になりそうな使い方もできたので、連想配列の代替としては十分使えそうです。
他にも、Dictinoary型のドキュメントを読んでいると、PHPの配列関連関数てきな動作もひととおりできそうでした。
以下、いくつかサンプル置いておきます。
★ キーを指定して値を取得するに
Debug.WriteLine(items["Apple"]);
★キーの存在確認if (items.ContainsKey("Apple"))
{
Debug.WriteLine("Apple あります。");
}
## 値の存在確認if (items.ContainsValue("りんご"))
{
Debug.WriteLine("りんご、あります。");
}

