C# 程序检查哈希表中是否存在值
The hashtable is an organized collection of key-value pairs wherein the keys are arranged as per the hash code of the key calculated using the hash function. While the keys should be non-null and unique in a hashtable, the values can be null and duplicate.
哈希表中的元素是通过键来访问的。在C#中,类"Hashtable"表示哈希表集合。这个类提供了各种属性和方法,我们可以使用它们来执行操作并访问哈希表中的数据。
在本文中,我们将看到如何确定哈希表中是否存在特定的值。
How to Check if Value Exists in Hashtable?
要检查哈希表中是否存在某个值,我们可以利用Hashtable类提供的“containsValue”方法。该方法返回一个布尔值,指示指定的值是否存在于哈希表中。
Let’s have a look at the method first before proceeding with programming examples.
ContainsValue方法
Syntax − public virtual bool ContainsValue (object value);
Description − used to find if the Hashtable contains a specified value.
参数 - 要在哈希表中定位的值(对象)。可以是空值。
返回值 − Boolean: true=> 哈希表中包含具有指定值的元素。
False=> 哈希表不包含指定值的元素。
命名空间 - System.Collections
Let’s now see few programming examples where we check if the specified value is present in the hashtable or not.
Example
检查值是否存在于哈希表中的第一个程序如下所示。
using System; using System.Collections; class Program { public static void Main(){ // Create a Hashtable Hashtable langCodes = new Hashtable(); // Add elements to the Hashtable langCodes.Add("C++", "CPlusPlus"); langCodes.Add("C#", "CSharp"); langCodes.Add("Java", "Java"); langCodes.Add("PL", "Perl"); // use ContainsValue method to check if the HashTable contains the //required Value or not. if (langCodes.ContainsValue("CSharp")) Console.WriteLine("langCodes hashtable contain the Value = CSharp"); else Console.WriteLine("langCodes hashtable doesn't contain the Value = CSharp"); } } 登录后复制