I have two questions:
What is the difference between a Hashtable and a Dictionary?
Is there any possible way to save either of these collections to disk?
I have two questions:
What is the difference between a Hashtable and a Dictionary?
Is there any possible way to save either of these collections to disk?
First of all, don't use a Hashtable. Use a HashSet instead. You can find it in the namespace System.Collections.Generic.
What is a Hash Map?
A Hash map (or Dictionary, as it's called in C#) is a data structure that allows you to look up one type of data by using another type of input. Basically, when you add an item to the dictionary, you specify both a key and a value. Then when you want to look up the value in the dictionary, you simply give it the key and it will give you the value that is associated with it.
For example, if you have a bunch of Product objects that you want to be able to look up by their UPCs, you would add the products to your Dictionary with the Product as the value and the UPC number as the key.
A HashSet on the other hand, does not store pairs of keys and values. It simply stores items. A hash set (or any set, for that matter) ensures that when you add items to the collection, there will be no duplicates.
When I Add Item's In Hash Table , Can I Save It As New File And Restore The Original Item's?
First of all, don't use a Hashtable. Use a HashSet
instead. You can find it in the namespace System.Collections.Generic
. To use it, you simply add items to it the same way you do with any other collection.
Like the other collections, the HashSet
supports Serialization (Serialization is when you take an object and convert it to a string of bytes so it can be saved to a file or sent over the internet). Here's a sample program that shows serialization of a hash-set:
using System;
using System.Collections.Generic;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
namespace HashSetSerializationTest
{
class Program
{
static void Main(string[] args)
{
var set = new HashSet<int>();
set.Add(5);
set.Add(12);
set.Add(-50006);
Console.WriteLine("Enter the file-path:");
string path = Console.ReadLine();
Serialize(path, set);
HashSet<int> deserializedSet = (HashSet<int>)Deserialize(path);
foreach (int number in deserializedSet)
{
Console.WriteLine($"{number} is in original set: {set.Contains(number)}");
}
Console.ReadLine();
}
static void Serialize(string path, object theObjectToSave)
{
using (Stream stream = File.Create(path))
{
var formatter = new BinaryFormatter();
formatter.Serialize(stream, theObjectToSave);
}
}
static object Deserialize(string path)
{
using (Stream stream = File.OpenRead(path))
{
var formatter = new BinaryFormatter();
return formatter.Deserialize(stream);
}
}
}
}
In order to serialize anything, you'll need to include System.IO
and System.Runtime.Serialization.Formatters.Binary
.