Click here to Skip to main content
Licence 
First Posted 7 Jul 2002
Views 131,479
Bookmarked 38 times

Hash Table and Serialization in .NET

By | 7 Jul 2002 | Article
This article introduces hash table and serialization in .NET

Sample Image - Phonebook.jpg

Introduction

This article introduces and describes the use of hash table and serialization in .NET using C#. The sample application used here is a Phone Book application. Phone Book application is a console application that allows a user to add, view, list, and delete entries containing names and phone numbers.

A hash table is a collection of key-value pairs. In .NET, the class that implements a hash table is the Hashtable class. Elements can be added to the hash table by calling the Add method passing in the key-value pairs that you want to add. The objects used as keys must implement Object.Equals and Object.GetHashCode methods.

private Hashtable table = new Hashtable();
		
public void AddEntry(BookEntry entry)
{
   table.Add( entry.GetPerson(), entry );
}	

Once the hash table is populated, you can search and retrieve elements in it by calling the indexer for the Hashtable class.

public BookEntry GetEntry(Person key)
{
   return (BookEntry) table[key];
}			

Entries can be removed from the hash table by calling the Remove method which takes a key identifying the element you want to remove.

public void DeleteEntry(Person key)
{
   table.Remove( key );
}	

The populated hash table can be saved to a file by using serialization. Serialization is the process of converting an object into a linear sequence of bytes for either storage or transmission to another location. This task can be performed using BinaryFormater class which serializes the hash table object to the file stream.

public void Save()
{
   Stream s = File.Open("Phone.bin", FileMode.Create, FileAccess.ReadWrite);
   BinaryFormatter b = new BinaryFormatter();
   b.Serialize(s, table);
   s.Close();      
}		

The hash table object can be recovered back from the file by using Deserialize method as shown below.

    s = File.Open("Phone.bin", FileMode.Open, FileAccess.Read);
    BinaryFormatter b = new BinaryFormatter();
    table = (Hashtable) b.Deserialize(s);

I hope you enjoy this brief introduction on hash table and serialization in .NET.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here

About the Author

Liong Ng

Web Developer

United States United States

Member



Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board. (secure sign-in)
 
Search this forum  
 FAQ
    Noise  Layout  Per page   
  Refresh
QuestionHow can we deserialize the object that not matched with the original structrure of the object that has been serialized ? PinmemberBudi Sentosa20:34 23 Feb '09  
Questionhw can i reset the integer "value" of key in a hash table using c#? Pinmembermerryjoy00020:05 23 Feb '09  
QuestionHow can i Clear only the values of a key in hash table using c# Pinmembermerryjoy00018:32 23 Feb '09  
Questionhas anyone found a Deserialization error and fixed it? Pinmemberdesnu13:44 9 Jul '04  
AnswerRe: has anyone found a Deserialization error and fixed it? Pinmemberhack.root15:04 5 Dec '05  
GeneralRemoving within a ForEach not possible Pinmemberaberglas8:10 6 Jun '03  
GeneralRe: Removing within a ForEach not possible Pinmemberleppie9:00 6 Jun '03  
AnswerRe: Removing within a ForEach not possible Pinmemberhack.root18:48 5 Dec '05  
It is not a problem for good programmer.
 
The main idea is not to REALLY try to remove from collection, but force behave it as if it didn't never had that elements. Delete elements only at Compact is als a good idea.
 
The code here:
 

    public struct HashtableKeyPair<T, U>

    {

      T key;

      U val;

 

      public HashtableKeyPair(T key, U val)

      {

        this.key = key;

        this.val = val;

      }

 

      public T Key { get { return key; } }

      public U Value { get { return val; } }

    }

 

    public class Hashtable<T, U>: System.Collections.Hashtable

    {

      public Hashtable() : base() { }

 

      public Hashtable(IEnumerable<HashtableKeyPair<T, U>?> keyPairs)

      {

        foreach (HashtableKeyPair<T, U>? keyPair in keyPairs)

          if (keyPair.HasValue)

            this[keyPair.Value.Key] = keyPair.Value.Value;

      }

 

      public IEnumerable<HashtableKeyPair<T, U>> KeyPairs

      {

        get

        {

          foreach (HashtableKeyPair<T, U> keyPair in base.Values)

              yield return keyPair;

        }

      }

 

      public U this[T key]

      {

        get { return ((HashtableKeyPair<T, U>)base[key]).Value; }

        set

        {

          base[key] = new HashtableKeyPair<T, U>(key, value);

        }

      }

 

      public HashtableKeyPair<T, U>? this[T key, Predicate<HashtableKeyPair<T, U>?> match]

      {

        get

        {

          if (base[key] != null)

          {

            HashtableKeyPair<T, U> obj = (HashtableKeyPair<T, U>)base[key];

            if (match(obj))

              return obj;

          }

          return null;

        }

      }

 

      public Hashtable<T, U> GetMatchedHashtable(Predicate<HashtableKeyPair<T, U>?> match)

      {

        return new Hashtable<T, U>(Match(match));

      }

 

      public IEnumerable<HashtableKeyPair<T, U>?> Match(Predicate<HashtableKeyPair<T, U>?> match)

      {

        foreach (T key in Keys)

          if (this[key, match].HasValue)

            yield return this[key, match].Value;

      }

 

      public void Remove(T key)

      {

        base[key] = null;

      }

 

      private Predicate<HashtableKeyPair<T, U>?> hasValues = delegate(HashtableKeyPair<T, U>? obj) { return obj.HasValue; };

 

      public void Compact()

      {     

        Hashtable<T, U> hashtable = new Hashtable<T, U>(Match(hasValues));

 

        base.Clear();

 

        foreach (HashtableKeyPair<T, U> keyPair in hashtable.KeyPairs)

          this[keyPair.Key] = keyPair.Value;

      }

    }

 
Usage:
 

      Hashtable<int, int> myhashtable = new Hashtable<int, int>();

 

      myhashtable[0] = 1;

      myhashtable[1] = 4;

      myhashtable[2] = 9;

      myhashtable[3] = 16;

 

      Predicate<HashtableKeyPair<int, int>?> even = delegate(HashtableKeyPair<int, int>? obj) { return obj.HasValue && (obj.Value.Value % 2 == 1) == true; };

      foreach (HashtableKeyPair<int, int> keyPair in myhashtable.GetMatchedHashtable(even).KeyPairs)

      {

        myhashtable.Remove(keyPair.Key);

      }

 

      myhashtable.Compact();


Question"^" What does this mean ? PinmemberCypher0:11 21 Feb '03  
AnswerRe: "^" What does this mean ? PinmemberLiong10:45 23 Feb '03  
GeneralWhile your at it, explain the HCP PinmemberSoliant15:03 27 Nov '02  

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Permalink | Advertise | Privacy | Mobile
Web01 | 2.5.120529.1 | Last Updated 8 Jul 2002
Article Copyright 2002 by Liong Ng
Everything else Copyright © CodeProject, 1999-2012
Terms of Use
Layout: fixed | fluid