c#

c#怎么判断字典里是否有某个值

小亿
193
2024-03-12 10:39:24
栏目: 编程语言

在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"的条目。最后根据判断结果输出相应的提示信息。

0
看了该问题的人还看了