L’HashTable è una classe offerta dal framework .NET presente all’interno del namespace System.Collections e ci consente di creare una lista in memoria (non salvata su disco) di elementi composti da una chiave e da un valore.
Ora vediamo come usarle senza disperderci in spiegazioni ma usando codice:
using System.Collections ;
…
private Hashtable _hashTable = new Hashtable() ;
Ora vediamo come aggiungere un valore:
_hashTable.Add( <chiave> , <valore> ) ;
Ricordo, che in base alla definizione del metodo Add possiamo aggiungere qualsiasi elemento sia come chiave (a patto che sia univoco) che come valore (qua i duplicati sono ammessi)
_hashTable.Add( object key , object value ) ;
Attenzione, il valore di <chiave> deve esser univoco all’interno della lista! Per veder se è già presente è molto semplice:
if( _hashTable.Contains( <chiave> ) )
{
// La chiave <chiave> è già presente.
// Non è possibile inserirla nuovamente.
// Possiamo però modificare il suo valore attuale.
_hashTable[ <chiave> ] = <nuovovalore> ;
}
Supponiamo di voler scorrere tutti gli elementi della HashTable:
foreach( DictionaryEntry dictionaryEntry in _hashTable )
{
Object oKey = dictionaryEntry.Key ;
Object oValue = dictionaryEntry.Value ;
// Elaborazione
}
Prima di concludere, vediamo un esempio “concreto e pratico”:
private void SetValue( string MyKey , string MyValue )
{
if( _hashTable.Contains( MyKey ) )
{
_hashTable[ MyKey ] = MyValue ;
}
else
{
_hashTable.Add( MyKey , MyValue ) ;
}
}
Commenti Recenti