C#程式檢查雜湊表中是否存在值
雜湊表是有組織的鍵值對集合,其中鍵根據使用雜湊函式計算的鍵的雜湊碼進行排列。雖然鍵在雜湊表中應該是唯一的且非空,但值可以為空並且可以重複。
雜湊表中的元素使用鍵進行訪問。在 C# 中,“Hashtable” 類表示雜湊表集合。此類提供了各種屬性和方法,我們可以使用它們來執行操作和訪問雜湊表中的資料。
在本文中,我們將瞭解如何確定特定值是否出現在雜湊表中。
如何在雜湊表中檢查值是否存在?
要檢查值是否在雜湊表中存在,我們可以使用 Hashtable 類提供的“containsValue”方法。此方法返回一個布林值,指示指定值是否出現在雜湊表中。
在繼續程式設計示例之前,讓我們先看一下此方法。
ContainsValue 方法
語法 − public virtual bool ContainsValue (object value);
描述 − 用於查詢 Hashtable 是否包含指定值。
引數 − 要在雜湊表中查詢的值 (object)。可以是空值。
返回值 − 布林值:true => 雜湊表包含一個具有指定值的元素。
False => 雜湊表不包含具有指定值的元素。
名稱空間 − System.Collections
現在讓我們看幾個程式設計示例,在這些示例中,我們檢查指定值是否出現在雜湊表中。
示例
下面給出了第一個程式,用於檢查值是否出現在雜湊表中。
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");
}
}
上面的程式聲明瞭一個 langCodes 雜湊表,其中包含語言程式碼和語言名稱分別作為鍵和值。接下來,我們有一個“if”結構,它檢查值“CSharp”是否出現在雜湊表中。如果存在,它將相應地顯示訊息。
輸出
程式的輸出如下所示。
langCodes hashtable contain the Value = CSharp
由於值 = CSharp 出現在雜湊表中,因此程式給出了以上訊息。
現在將 ContainsValue 方法的引數更改為“C#”,即鍵而不是值。
if (langCodes.ContainsValue("C#"))
現在執行帶有此更改的上述程式。
輸出
在這種情況下,由於值“C#”不出現在雜湊表中,因此程式將返回相應的訊息。所以我們會得到 -
langCodes hashtable doesn't contain the Value = CSharp
示例
現在讓我們看下面的例子。
using System;
using System.Collections;
class Program {
public static void Main() {
// Create a Hashtable
Hashtable NumberNames = new Hashtable();
// Add elements to the Hashtable
NumberNames.Add(1, "One");
NumberNames.Add(3, "Three");
NumberNames.Add(5, "Five");
NumberNames.Add(7, "Seven");
// use ContainsValue method to check if the HashTable contains the
//required Value or not.
if (NumberNames.ContainsValue("Two"))
Console.WriteLine("NumberNames hashtable contain the Value = Two");
else
Console.WriteLine("NumberNames hashtable doesn't contain the Value = Two");
if (NumberNames.ContainsValue("Five"))
Console.WriteLine("NumberNames hashtable contain the Value = Five");
else
Console.WriteLine("NumberNames hashtable doesn't contain the Value = Five");
}
}
此程式有一個“NumberNames”表,其中數字作為鍵,其對應的名稱作為值。在這裡,我們首先使用“containsKey()”方法檢查雜湊表是否包含值 = Two。接下來,我們使用 containsKey() 方法檢查值 = “Five”。
輸出
程式的輸出如下所示。
NumberNames hashtable doesn't contain the Value = Two NumberNames hashtable contain the Value = Five
從程式中定義的雜湊表可以看出,它不包含值 = Two,但包含值 = Five。因此,程式相應地給出了訊息。
結論
因此,使用 C# 中 Hashtable 類的“containsKey()”方法,我們可以確定是否在雜湊表中存在具有特定值的元素。根據值是否存在,我們可以輸出相應的結果,或者在複雜程式的情況下,繼續執行相應的程式碼。
因此,當我們必須檢查指定值是否出現在雜湊表中,然後採取相應的行動時,“containsKey()”方法變得很有用。
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP