📌  相关文章
📜  C#|检查StringDictionary是否包含特定值

📅  最后修改于: 2021-05-30 00:20:03             🧑  作者: Mango

StringDictionary.ContainsValue(String)方法用于检查StringDictionary是否包含特定值

句法:

public virtual bool ContainsValue (string value);

在这里, value是要在StringDictionary中找到的值。该值可以为空。

返回值:如果StringDictionary包含具有指定值的元素,则该方法返回true ,否则返回false

下面的程序说明了StringDictionary.ContainsValue(String)方法的用法:

范例1:

// C# code to check if the
// StringDictionary contains
// a specific value
using System;
using System.Collections;
using System.Collections.Specialized;
  
class GFG {
  
// Driver code
public static void Main()
{
  
    // Creating a StringDictionary named myDict
    StringDictionary myDict = new StringDictionary();
  
    // Adding key and value into the StringDictionary
    myDict.Add("G", "Geeks");
    myDict.Add("F", "For");
    myDict.Add("C", "C++");
    myDict.Add("DS", "Data Structures");
    myDict.Add("N", "Noida");
  
    // Checking if "C++" is contained in
    // StringDictionary myDict
    if (myDict.ContainsValue("C++"))
        Console.WriteLine("StringDictionary myDict contains the value");
    else
        Console.WriteLine("StringDictionary myDict does not contain the value");
    }
}
输出:
StringDictionary myDict contains the value

范例2:

// C# code to check if the
// StringDictionary contains
// a specific value
using System;
using System.Collections;
using System.Collections.Specialized;
  
class GFG {
  
// Driver code
public static void Main()
{
  
    // Creating a StringDictionary named myDict
    StringDictionary myDict = new StringDictionary();
  
    // Adding key and value into the StringDictionary
    myDict.Add("G", "Geeks");
    myDict.Add("F", "For");
    myDict.Add("C", "C++");
    myDict.Add("DS", "Data Structures");
    myDict.Add("N", "Noida");
  
    // Checking if "null" is contained in
    // StringDictionary myDict
    // It should not raise any exception
    if (myDict.ContainsValue(null))
        Console.WriteLine("StringDictionary myDict contains the value");
    else
        Console.WriteLine("StringDictionary myDict does not contain the value");
    }
}
输出:
StringDictionary myDict does not contain the value

笔记:

  • 使用Object.Equals方法将StringDictionary的元素值与指定值进行比较。
  • 此方法是O(n)运算,其中n是Count。

参考:

  • https://docs.microsoft.com/zh-cn/dotnet/api/system.collections.specialized.stringdictionary.containsvalue?view=netframework-4.7.2