Hashtable optimizes lookup. It computes a hash of each key you add. It then uses this hash code to look up the element very quickly. It is an older .NET Framework type. It is slower than the generic Dictionary type.
Example:
Hide Copy Code
using System.Collections;
class Program
{
static Hashtable GetHashtable()
{
// Create and return new Hashtable.
Hashtable hashtable = new Hashtable();
hashtable.Add("Area", 1000);
hashtable.Add("Perimeter", 55);
hashtable.Add("Mortgage", 540);
return hashtable;
}
public static void Main()
{
Hashtable hashtable = GetHashtable();
// See if the Hashtable contains this key.
Console.WriteLine(hashtable.ContainsKey("Perimeter"));
// Test the Contains method. It works the same way.
Console.WriteLine(hashtable.Contains("Area"));
// Get value of Area with indexer.
int value = (int)hashtable["Area"];
// Write the value of Area.
Console.WriteLine(value);
}
}
Output:
True
True
1000
Dictionary
A dictionary is used where fast lookups are critical. The Dictionary type provides fast lookups with keys to get values. With it we use keys and values of any type, including ints and strings. Dictionary requires a special syntax form.
Dictionary is used when we have many different elements. We specify its key type and its value type. It provides good performance.
Example:
Hide Copy Code
class Dict
{
static void Main()
{
// Example Dictionary again
Dictionary<string, int> d = new Dictionary<string, int>()
{
{"Lion", 2}, {"dog", 1}};
// Loop over pairs with foreach
foreach (KeyValuePair<string, int> pair in d)
{
Console.WriteLine ("{0}, {1}",pair.Key, pair.Value);
}
foreach (var pair in d)
{
Console.WriteLine("{0}, {1}", pair.Key, pair.Value);
}
Console.ReadKey();
}
}
No comments:
Post a Comment