搜尋
首頁後端開發C#.Net教程如何使用指定鍵從 C# 中的 HashTable 集合中取得值

如何使用指定键从 C# 中的 HashTable 集合中获取值

A hashtable is a collection of key−value pairs. We can access key−value pairs using an iterator. We can also access the keys of the hashtable in a collection. Similarly, we can access the values in a hashtable. Given a hashtable, it is also possible to access the value of a specified key or matching key of a specified value.

讓我們討論一下如何在給定鍵的雜湊表集合中存取一個值。

如何使用指定的鍵從Hashtable集合中取得值?

Here, we have to obtain a value from the key−value pair of hashtables when a key is given.

考慮以下哈希表。

{“US", "New York"}
{"FR", "Paris"}
{"UK", "London"}
{"IN", "Mumbai"}
{"GER", "Berlin"}

Here, let's suppose we have to find the value for the key “UK”. So we have to traverse the hashtable to find out if the hashtable contains the key = UK. Once the key=” UK” is found, we can access its corresponding value as hashtable[key].

Example

The program that exactly performs the above operation is shown below −

using System;
using System.Collections;
class MyHashTable {
   // Main Method
   static public void Main() {

      // Create a hashtable instance
      Hashtable Citytable = new Hashtable();

      // Adding key/value pair in the hashtable using Add() method
      Citytable.Add("US", "New York");
      Citytable.Add("FR", "Paris");
      Citytable.Add("UK", "London");
      Citytable.Add("IN", "Mumbai");
      Citytable.Add("GER", "Berlin");
      
      String key;
      Console.WriteLine("Enter the key whose value is to be printed:");
      key = Console.ReadLine();
      if(key != ""){
         if(Citytable.Contains(key) == true){
         string keyval = (string)Citytable[key];
         Console.WriteLine("The value of key {0} = {1}", key,keyval);
      }
      else
         Console.WriteLine ("Value for the key= {0} does not exist", key);
      }    
      Console.ReadKey();
   }
}

在上面的程式中,我們定義了一個雜湊表。然後使用者輸入要取得值的鍵。一旦鍵被讀取為輸入,我們首先確定鍵是否為null或空。這是因為哈希表的鍵不應為null。因此,如果使用者輸入空值,我們將不會繼續尋找值。

因此,如果鍵不為空,我們將檢查雜湊表是否包含指定的鍵。為此,我們使用C#中的雜湊表集合方法 Contains() ,如果鍵存在於雜湊表中則傳回true,如果鍵不存在則傳回false。

如果 Contains() 方法傳回 true,則我們只需存取該特定鍵的值。

string keyval = (string)Citytable[key];

Then this value is displayed to the user.

Output

#
Enter the key whose value is to be printed:
FR
The value of key FR = Paris

在這個輸出中,使用者執行了程式並輸入了鍵值為FR。由於這個鍵已經存在於雜湊表中,因此該鍵對應的值成功回傳。

現在,如果我們輸入一個在雜湊表中不存在的鍵值?

Let’s execute the program again. Now we do not have a key in our hashtable for the country Canada. Let’s enter the key as CAN for Canada. The output is shown below.

Output

#
Enter the key whose value is to be printed:
CAN
Value for the key= CAN do not exist

在這裡,由於雜湊表中不包含 key=CAN,程式傳回值不存在的訊息。

以這種方式,我們可以開發一個互動式程序,從哈希表集合中找到指定鍵的值。

Let’s take another example to find the value given a key using a hashtable.

Here we will consider the following hashtable containing numbers and their corresponding number names.

{“1.1", "One point One"}
{"1.2", "One point Two"}
{"1.3", "One point Three"}
{"1.4", "One point Four"}
{"1.5", "One point Five"}

類似於前面的範例,這裡我們也會要求使用者輸入要尋找值的鍵,然後在雜湊表中搜尋指定的鍵並顯示其值。

Example 2

Below given is the program to do that same.

using System;
using System.Collections;
class MyHashTable {
   // Main Method
   static public void Main() {

      // Create a hashtable instance
      Hashtable Numbernames = new Hashtable();

      // Adding key/value pair in the hashtable using Add() method
      Numbernames.Add("1.1", "One point One");
      Numbernames.Add("1.2", "One point Two");
      Numbernames.Add("1.3", "One point Three");
      Numbernames.Add("1.4", "One point Four");
      Numbernames.Add("1.5", "One point Five");

      String key = "1.4";
      if(key != ""){
          if(Numbernames.Contains(key) == true){
              string keyval = (string)Numbernames[key];
              if(keyval != "")
                 Console.WriteLine("The value of key {0} = {1}", key,keyval);
              else
                 Console.WriteLine("The value for key = {0} does not exist", key);
          }
          else
             Console.WriteLine ("The key= {0} does not exist in the NumberNames hashtable", key);
      }    
      Console.ReadKey();
   }
}

The program is the same as the previous example except for the hashtable and an extra condition we have specified to check for an empty value. This is because it can so happen that a specified key. This is because it can so happen that a specified key might be preent in the happen mbutent in key might corresponding value might be empty. Secondly, we are not reading user input in this program, instead, we have directly used a key = “1.4” and we print out the value of this key. So we introduced one value. Hence this program now checks −

  • If the key specified is empty

  • #If the key is not empty, the program checks if the hashtable contains the key.

  • If the hashtable contains the key, then it retrieves the value for the key. If the value is not empty, then the program displays the value.

  • If the value is empty, the appropriate message is displayed.

#Output

#
The value of key 1.4 = One point Four

This output is generated when we specify a correct key that is present in the hashtable.

在本文中,我們看到如何透過鍵從雜湊表集合中取得值。我們還透過幾個程式範例展示了不同的輸出,以清晰地說明概念。在我們接下來的文章中,我們將繼續討論哈希表的相關主題。

以上是如何使用指定鍵從 C# 中的 HashTable 集合中取得值的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述
本文轉載於:tutorialspoint。如有侵權,請聯絡admin@php.cn刪除
C#作為.NET語言:生態系統的基礎C#作為.NET語言:生態系統的基礎May 02, 2025 am 12:01 AM

C#是微軟在2000年發布的編程語言,旨在結合C 的強大功能和Java的簡潔性。 1.C#是一種類型安全、面向對象的編程語言,支持封裝、繼承和多態。 2.C#的編譯過程將代碼轉化為中間語言(IL),然後在.NET運行時環境(CLR)中即時編譯成機器碼執行。 3.C#的基本用法包括變量聲明、控制流和函數定義,而高級用法涵蓋異步編程、LINQ和委託等。 4.常見錯誤包括類型不匹配和空引用異常,可通過調試器、異常處理和日誌記錄來調試。 5.性能優化建議包括使用LINQ、異步編程和提高代碼可讀性。

c#vs. .net:澄清關鍵差異和相似之處c#vs. .net:澄清關鍵差異和相似之處May 01, 2025 am 12:12 AM

C#是一種編程語言,而.NET是一個軟件框架。 1.C#由微軟開發,適用於多平台開發。 2..NET提供類庫和運行時環境,支持多語言。兩者協同工作,構建現代應用。

超越炒作:評估C#.NET的當前作用超越炒作:評估C#.NET的當前作用Apr 30, 2025 am 12:06 AM

C#.NET是一個強大的開發平台,結合了C#語言和.NET框架的優勢。 1)它廣泛應用於企業應用、Web開發、遊戲開發和移動應用開發。 2)C#代碼編譯成中間語言後由.NET運行時環境執行,支持垃圾回收、類型安全和LINQ查詢。 3)使用示例包括基本控制台輸出和高級LINQ查詢。 4)常見錯誤如空引用和類型轉換錯誤可以通過調試器和日誌記錄解決。 5)性能優化建議包括異步編程和優化LINQ查詢。 6)儘管面臨競爭,C#.NET通過不斷創新保持其重要地位。

C#.NET的未來:趨勢和機遇C#.NET的未來:趨勢和機遇Apr 29, 2025 am 12:02 AM

C#.NET的未來趨勢主要集中在雲計算、微服務、AI和機器學習集成以及跨平台開發三個方面。 1)雲計算和微服務:C#.NET通過Azure平台優化雲環境表現,支持構建高效微服務架構。 2)AI和機器學習集成:借助ML.NET庫,C#開發者可在應用中嵌入機器學習模型,推動智能化應用發展。 3)跨平台開發:通過.NETCore和.NET5 ,C#應用可在Windows、Linux和macOS上運行,擴展部署範圍。

C#.NET開發今天:趨勢和最佳實踐C#.NET開發今天:趨勢和最佳實踐Apr 28, 2025 am 12:25 AM

C#.NET開發的最新動態和最佳實踐包括:1.異步編程提高應用響應性,使用async和await關鍵字簡化非阻塞代碼;2.LINQ提供強大查詢功能,通過延遲執行和表達式樹高效操作數據;3.性能優化建議包括使用異步編程、優化LINQ查詢、合理管理內存、提升代碼可讀性和維護性、以及編寫單元測試。

C#.NET:使用.NET生態系統構建應用程序C#.NET:使用.NET生態系統構建應用程序Apr 27, 2025 am 12:12 AM

如何利用.NET構建應用?使用.NET構建應用可以通過以下步驟實現:1)了解.NET基礎知識,包括C#語言和跨平台開發支持;2)學習核心概念,如.NET生態系統的組件和工作原理;3)掌握基本和高級用法,從簡單控制台應用到復雜的WebAPI和數據庫操作;4)熟悉常見錯誤與調試技巧,如配置和數據庫連接問題;5)應用性能優化與最佳實踐,如異步編程和緩存。

C#作為多功能.NET語言:應用程序和示例C#作為多功能.NET語言:應用程序和示例Apr 26, 2025 am 12:26 AM

C#在企業級應用、遊戲開發、移動應用和Web開發中均有廣泛應用。 1)在企業級應用中,C#常用於ASP.NETCore開發WebAPI。 2)在遊戲開發中,C#與Unity引擎結合,實現角色控制等功能。 3)C#支持多態性和異步編程,提高代碼靈活性和應用性能。

C#.NET用於網絡,桌面和移動開發C#.NET用於網絡,桌面和移動開發Apr 25, 2025 am 12:01 AM

C#和.NET適用於Web、桌面和移動開發。 1)在Web開發中,ASP.NETCore支持跨平台開發。 2)桌面開發使用WPF和WinForms,適用於不同需求。 3)移動開發通過Xamarin實現跨平台應用。

See all articles

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

Video Face Swap

Video Face Swap

使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱工具

記事本++7.3.1

記事本++7.3.1

好用且免費的程式碼編輯器

SublimeText3 Mac版

SublimeText3 Mac版

神級程式碼編輯軟體(SublimeText3)

SecLists

SecLists

SecLists是最終安全測試人員的伙伴。它是一個包含各種類型清單的集合,這些清單在安全評估過程中經常使用,而且都在一個地方。 SecLists透過方便地提供安全測試人員可能需要的所有列表,幫助提高安全測試的效率和生產力。清單類型包括使用者名稱、密碼、URL、模糊測試有效載荷、敏感資料模式、Web shell等等。測試人員只需將此儲存庫拉到新的測試機上,他就可以存取所需的每種類型的清單。

SublimeText3漢化版

SublimeText3漢化版

中文版,非常好用

Dreamweaver Mac版

Dreamweaver Mac版

視覺化網頁開發工具