C#で辞書に特定の値が存在するかどうかを判断する方法は何ですか?
C#では、ContainsValueメソッドを使用して、辞書に特定の値が含まれているかどうかを判断することができます。以下は、サンプルコードです:
using System;
using System.Collections.Generic;
class Program
{
static void Main()
{
Dictionary<int, string> dictionary = new Dictionary<int, string>();
dictionary.Add(1, "apple");
dictionary.Add(2, "banana");
dictionary.Add(3, "orange");
string searchValue = "banana";
bool containsValue = dictionary.ContainsValue(searchValue);
if (containsValue)
{
Console.WriteLine($"The dictionary contains the value '{searchValue}'.");
}
else
{
Console.WriteLine($"The dictionary does not contain the value '{searchValue}'.");
}
}
}
上記の例では、まずキーと値のペアを含む辞書を作成し、その後にContainsValueメソッドを使用して、”banana”の値を持つエントリーが辞書内に含まれているかをチェックします。最後に判断結果に応じて対応するメッセージを出力します。