IDictionary<TKey,TValue>.ContainsKey(TKey) メソッド

定義

指定したキーの要素が IDictionary<TKey,TValue> に格納されているかどうかを確認します。

C#
public bool ContainsKey (TKey key);

パラメーター

key
TKey

IDictionary<TKey,TValue> 内で検索されるキー。

戻り値

指定したキーを持つ要素を true が保持している場合は IDictionary<TKey,TValue>。それ以外の場合は false

例外

keynullです。

次のコード例は、 メソッドを使用して、 メソッドを ContainsKey 呼び出す前にキーが存在するかどうかをテストする方法を Add 示しています。 また、 メソッドを TryGetValue 使用する方法も示します。これは、プログラムがディクショナリに含まれていないキー値を頻繁に試行する場合に、より効率的に値を取得する方法です。 最後に、プロパティ (C# のインデクサー) を使用して項目を Item[] 挿入する方法を示します。

このコードは、コンパイルおよび実行できるより大きな例の一部です。 以下を参照してください。System.Collections.Generic.IDictionary<TKey,TValue>

C#
// ContainsKey can be used to test keys before inserting
// them.
if (!openWith.ContainsKey("ht"))
{
    openWith.Add("ht", "hypertrm.exe");
    Console.WriteLine("Value added for key = \"ht\": {0}",
        openWith["ht"]);
}
C#
// When a program often has to try keys that turn out not to
// be in the dictionary, TryGetValue can be a more efficient
// way to retrieve values.
string value = "";
if (openWith.TryGetValue("tif", out value))
{
    Console.WriteLine("For key = \"tif\", value = {0}.", value);
}
else
{
    Console.WriteLine("Key = \"tif\" is not found.");
}
C#
// The indexer throws an exception if the requested key is
// not in the dictionary.
try
{
    Console.WriteLine("For key = \"tif\", value = {0}.",
        openWith["tif"]);
}
catch (KeyNotFoundException)
{
    Console.WriteLine("Key = \"tif\" is not found.");
}

注釈

実装は、オブジェクトの等価性を決定する方法によって異なる場合があります。たとえば、 クラスでは を List<T> 使用 Comparer<T>.Defaultしますが、 Dictionary<TKey,TValue> クラスを使用すると、キーの比較に使用する実装をユーザーが指定 IComparer<T> できます。

実装は、 を 許可 key するかどうかによって異なる場合があります null

適用対象

製品 バージョン
.NET Core 1.0, Core 1.1, Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9
.NET Framework 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
.NET Standard 1.0, 1.1, 1.2, 1.3, 1.4, 1.5, 1.6, 2.0, 2.1
UWP 10.0