C# Hashtabel met voorbeelden

โšก Slimme samenvatting

Hashtable in C# is a collection from the System.Collections namespace that stores data as key-value pairs, where each unique key maps to a value and the key provides fast lookup of that stored value.

  • ๐Ÿ“š Key-value pairs: A Hashtable stores two values per element, a key and its value, instead of the single value held by a stack or array list.
  • โž• Adding elements: The Add method inserts a key and a value together, and every key inside the Hashtable must be unique.
  • ๐Ÿ‘€ ContainsKey and ContainsValue: These methods return true or false so you can test whether a key or a value already exists.
  • ๐Ÿ” Reading values: The Keys property with an ICollection, or a DictionaryEntry loop, lets you read every stored value in turn.
  • ๏ธ Methods and properties: Remove, Clear, Count, Keys, and Values manage and inspect the contents of the Hashtable.
  • ๐Ÿค– AI-assistentie: GitHub Copilot scaffolds Hashtable code, while modern C# and ML.NET favor the generic Dictionary for type-safe key-value data.

C# Hashtabel

Wat is hashtabel in C#?

Een hashtabel is een speciale verzameling die wordt gebruikt om sleutelwaarde-items op te slaan. Dus in plaats van slechts รฉรฉn waarde op te slaan, zoals de stapel, de arraylijst en de wachtrij, slaat de hashtabel twee waarden op. Deze 2 waarden vormen een onderdeel van de hashtabel.

Hieronder vindt u enkele voorbeelden van hoe de waarden van een hashtabel eruit kunnen zien.

{ "001" , ".Net" }
{ "002" , ".C#" }
{ "003" , "ASP.Net" }

Hierboven hebben we 3 sleutelwaardeparen. De toetsen van elk element zijn respectievelijk 001, 002 en 003. De waarden van elk sleutelwaardepaar zijn โ€œ. Netโ€œ, โ€œC#โ€ en โ€œASP.Netโ€ respectievelijk.

Laten we de bewerkingen die beschikbaar zijn voor de Hashtable-verzameling eens nader bekijken.

Verklaring van de hashtabel

De declaratie van een hashtabel wordt hieronder weergegeven. Met behulp van het Hashtable Datatype wordt een Hashtabel gemaakt. Het trefwoord โ€œnieuwโ€ wordt gebruikt om een โ€‹โ€‹object van een hashtabel te maken. Het object wordt vervolgens toegewezen aan de variabele ht.

Hashtable ht = new Hashtable()

Elementen toevoegen aan de hashtabel

De Add-methode wordt gebruikt om een โ€‹โ€‹element toe te voegen aan de queue. De algemene syntaxis van de verklaring wordt hieronder gegeven

HashTable.add("key","value")

Voorbeeld 1:

Onthoud dat elk element van de hashtabel uit twee waarden bestaat: de ene is de sleutel en de andere is de waarde.

Laten we dit nu op codeniveau zien werken. Alle onderstaande code wordt naar onze Console-applicatie geschreven.

De code wordt naar ons Program.cs-bestand geschreven. In het onderstaande programma zullen we de code schrijven om te zien hoe we de bovengenoemde methoden kunnen gebruiken.

Voor nu zullen we in ons voorbeeld alleen kijken hoe we een hashtabel kunnen maken, elementen aan de hashtabel kunnen toevoegen en deze dienovereenkomstig kunnen weergeven.

Hashtabel in C#

using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DemoApplication
{
 class Program
 {
  static void Main(string[] args)
  {
   Hashtable ht = new Hashtable();
   ht.Add("001",".Net");
   ht.Add("002","C#");
   ht.Add("003","ASP.Net");

   ICollection keys = ht.Keys;

   foreach (String k in keys)
   {
    Console.WriteLine(ht[k]);
   }
    Console.ReadKey();
   }
 }
}

Code Uitleg:-

  1. Eerst declareren we de hashtabelvariabele met behulp van het gegevenstype Hashtable door het trefwoord 'Nieuw' te gebruiken. De naam van de variabele die wordt gedefinieerd is 'ht'.
  2. Vervolgens voegen we elementen toe aan de hashtabel met behulp van de Add-methode. Houd er rekening mee dat we zowel een sleutel- als een waarde-element moeten toevoegen wanneer we iets aan de hashtabel toevoegen.
  3. Er is geen directe manier om de elementen van een hashtabel weer te geven.
    • Om de hashtabel weer te geven, moeten we eerst de lijst met sleutels (001, 002 en 003) uit de hashtabel halen.
    • Dit gebeurt via de ICollection-interface. Dit is een speciaal gegevenstype dat kan worden gebruikt om de sleutels van hashtabelcollecties op te slaan. Vervolgens wijzen we de sleutels van de hashtabelverzameling toe aan de variabele 'sleutels'.
  4. Vervolgens krijgen we voor elke sleutelwaarde de bijbehorende waarde in de hashtabel door de instructie ht[k] te gebruiken.

Als de bovenstaande code correct is ingevoerd en het programma wordt uitgevoerd, wordt de volgende uitvoer weergegeven.

Output:

Hashtabel in C#

Laten we eens kijken naar enkele andere methoden die beschikbaar zijn voor hashtabellen.

Bevat sleutel

Deze methode wordt gebruikt om te zien of een sleutel aanwezig is in de hashtabel. Hieronder vindt u de algemene syntaxis van deze verklaring. De instructie retourneert true als de sleutel bestaat, anders wordt de waarde false geretourneerd.

Hashtable.Containskey(key)

Bevatwaarde

Deze methode wordt gebruikt om te zien of een waarde aanwezig is in de hashtabel. Hieronder vindt u de algemene syntaxis van deze verklaring. De instructie retourneert true als de waarde bestaat, anders wordt de waarde false geretourneerd.

Hashtable.ContainsValue(value)

Voorbeeld 2:

Laten we de code in ons Console applicatie om te laten zien hoe we de methoden โ€œContainskeyโ€ en โ€œContainsValueโ€ kunnen gebruiken.

Hashtabel in C#

using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DemoApplication
{
 class Program
 {
  static void Main(string[] args)
  {
   Hashtable ht = new Hashtable();
   ht.Add("001",".Net");
   ht.Add("002","C#");
   ht.Add("003","ASP.Net");

   Console.WriteLine(ht.ContainsKey("001"));
   Console.WriteLine(ht.ContainsValue("C#"));
   Console.ReadKey();
   }
 }
}

Code Uitleg:-

  1. Eerst gebruiken we de methode ContainsKey om te zien of de sleutel aanwezig is in de hashtabel. Deze methode retourneert true als de sleutel aanwezig is in de hashtabel. Deze methode zou true moeten retourneren, omdat de sleutel wel in de hashtabel voorkomt.
  2. Vervolgens gebruiken we de methode BevatValue om te zien of de waarde aanwezig is in de hashtabel. Deze methode retourneert 'true' omdat de waarde wel in de hashtabel voorkomt.

Als de bovenstaande code correct is ingevoerd en het programma wordt uitgevoerd, wordt de volgende uitvoer weergegeven.

Output:

Hashtabel in C#

Uit de uitvoer kunt u duidelijk zien dat zowel de sleutel als de waarde waarnaar wordt gezocht, aanwezig zijn in de hashtabel.

How to Loop Through a C# Hashtable

The examples above read values through the Keys collection, but a Hashtable can be walked in a cleaner way. A foreach loop over a DictionaryEntry hands you the key and the value of every element together in a single pass, which is the most common way to read a Hashtable.

Stap 1) Create a Hashtable and add three key-value pairs to it.

Stap 2) Loop over the Hashtable with a DictionaryEntry variable, then read the Key and Value properties of each entry.

using System;
using System.Collections;

namespace DemoApplication
{
 class Program
 {
  static void Main(string[] args)
  {
   Hashtable ht = new Hashtable();
   ht.Add("101", "Java");
   ht.Add("102", "Python");
   ht.Add("103", "Kotlin");

   foreach (DictionaryEntry entry in ht)
   {
    Console.WriteLine(entry.Key + " - " + entry.Value);
   }
   Console.ReadKey();
  }
 }
}

Code Uitleg:-

  1. A Hashtable named ht is created, and three key-value pairs are inserted with the Add method.
  2. The foreach loop assigns each element to a DictionaryEntry, whose Key and Value properties expose the two halves of the pair.

When the program runs, it prints each key next to its value, such as 101 โ€“ Java. Because a Hashtable does not keep insertion order, the pairs may appear in a different sequence than they were added. To read only the keys, loop over the Keys collection, and to read only the values, loop over the Values collection instead.

C# Hashtable Methods and Properties

The Hashtable class exposes a small set of methods and properties that cover almost every task you will need, from adding and removing pairs to checking membership and counting elements. The most useful members are listed below.

Lid Type Beschrijving
Add(key, value) Methode Inserts a new key and value pair; the key must be unique.
Verwijder(sleutel) Methode Deletes the element that matches the specified key.
Duidelijk() Methode Removes every key-value pair from the Hashtable.
ContainsKey(key) Methode Returns true when the given key is present.
ContainsValue(value) Methode Returns true when the given value is present.
Tellen Eigendom Gets the number of key-value pairs stored.
Keys Eigendom Returns a collection of all the keys.
Waarden Eigendom Returns a collection of all the values.

Because each key is hashed, ContainsKey and the indexer locate an element in near constant time, which is what makes a Hashtable so useful for fast lookups.

Difference Between Hashtable and Dictionary in C#

A Hashtable and a Dictionary both store key-value pairs, and both belong to the wider family of C# collecties. The important difference is type safety, and that difference decides which one you should reach for in new code.

  • Type veiligheid: A Hashtable stores every key and value as an object, while Dictionary<TKey, TValue> is generic, so the compiler checks the types you use.
  • namespace: Hashtable lives in System.Collections, whereas Dictionary lives in System.Collections.Generic.
  • Boxing: A Hashtable boxes value types such as int, but a generic Dictionary stores them directly and avoids that cost.
  • prestaties: Dictionary is usually faster because it needs no casting back from object when you read a value.
  • Draadveiligheid: Hashtable offers the Synchronized wrapper for one writer with many readers, while concurrent code usually chooses ConcurrentDictionary.

For any new project, the generic Dictionary is the recommended choice, and the non-generic Hashtable mainly appears in older code.

Veelgestelde vragen

The Remove method deletes the element with a given key and reduces Count by one. If the key does not exist, nothing happens, so call ContainsKey first when you must be sure the key is present.

No. Every key in a Hashtable must be unique. Calling Add with a key that already exists throws an ArgumentException. You can, however, store the same value under several different keys without any error.

A Hashtable supports one writer with many readers safely. For several writing threads, wrap it using Hashtable.Synchronized, or prefer ConcurrentDictionary from System.Collections.Concurrent, which handles concurrent reads and writes without external locks.

Looking up a value by key runs in near constant O(1) time on average, because the key is hashed to find its bucket. Heavy hash collisions can slow it down, but that is rare with well-distributed keys.

A value may be null, but a key cannot. Passing a null key to Add or the indexer throws an ArgumentNullException. Each key must also be unique and should not change while it is stored.

A Hashtable keeps no order, so it cannot be sorted in place. Copy its keys into a list or an ArrayList, sort that list, then read values by key. A SortedList keeps its entries ordered automatically.

Yes. GitHub Copilot writes Hashtable declarations, Add calls, and DictionaryEntry loops from a short comment or method name. It often suggests the generic Dictionary instead, since that is the recommended collection for new C# code.

ML.NET training data flows through typed collections and the IDataView pipeline rather than a Hashtable. However, hash-based key-value maps still support feature lookups, vocabulary encoding, and caching around a machine learning model.

Vat dit bericht samen met: