C#の辞書でキーを使って値を取得する方法は何ですか?

C#では、キーを使用して値を取得する際に、DictionaryのTryGetValueメソッドを使用するか、直接[key]インデックス演算子を使用することができます。

  1. TryGetValueメソッドを使用する。
Dictionary<string, int> dict = new Dictionary<string, int>();
dict.Add("key1", 100);
dict.Add("key2", 200);

int value;
if (dict.TryGetValue("key1", out value))
{
    Console.WriteLine("Value for key1: " + value);
}
  1. [key]を使用したインデックス演算子:
Dictionary<string, int> dict = new Dictionary<string, int>();
dict.Add("key1", 100);
dict.Add("key2", 200);

int value = dict["key1"];
Console.WriteLine("Value for key1: " + value);

注意:辞書で[key]検索操作を使用する際に、指定したキーが存在しない場合、KeyNotFoundException例外が発生します。そのため、例外を避けるためにはTryGetValueメソッドを使用するのがよいでしょう。

bannerAds