Dictionaryクラスを簡単に初期化するには?[C# 3.0].NET TIPS

» 2008年03月13日 05時00分 公開
[岸本真二郎デジタルアドバンテージ]

この記事は会員限定です。会員登録(無料)すると全てご覧いただけます。

「.NET TIPS」のインデックス

連載目次

 C# 2.0(.NET Framework 2.0に含まれるC#)以降では、ジェネリック・クラスの追加によりコレクションが非常に使いやすくなっている。その1つであるDictionaryジェネリック・クラス(System.Collections.Generic名前空間のDictionary<TKey, TValue>クラス)も利用頻度の高いクラスである。

 Dictionaryクラスは.NET Framework 1.xにあったHashTableクラスを進化させたもので、キーと値の組み合わせでデータを保持し、指定したキーからペアとなっている値を素早く取り出すことができる(参考:「TIPS:ハッシュテーブル(連想配列)を使うには?(Dictionaryクラス編)」)。

 このDictionaryクラスの初期化については、例えばリファレンス・マニュアルでは、次のようなサンプル・コードが記載されている。

Dictionary<string, string> openWith
    = new Dictionary<string, string>();

// Add some elements to the dictionary. There are no
// duplicate keys, but some of the values are duplicates.
openWith.Add("txt", "notepad.exe");
openWith.Add("bmp", "paint.exe");
openWith.Add("dib", "paint.exe");
openWith.Add("rtf", "wordpad.exe");

Dictionaryオブジェクトの初期化コード例

 このように、基本的にはAddメソッドを呼び出して、キーと値のペアを追加していく必要がある。

 これがC# 3.0では、次のようにして初期値を設定できるようになっている。

using System.Collections.Generic;

class sample
{
  Dictionary<string, string> openWith
     = new Dictionary<string, string>()
  {
    {"txt", "notepad.exe"},
    {"bmp", "paint.exe"},
    {"dib", "paint.exe"},
    {"rtf", "wordpad.exe"}
  };
}

C# 3.0におけるDictionaryオブジェクトの初期化

Copyright© Digital Advantage Corp. All Rights Reserved.

RSSについて

アイティメディアIDについて

メールマガジン登録

@ITのメールマガジンは、 もちろん、すべて無料です。ぜひメールマガジンをご購読ください。