在 C# 中,Dictionary 是一个泛型集合,通常用于存储键/值对。字典在System.Collection.Generics命名空间下定义。它本质上是动态的,这意味着字典的大小会根据需要增加。
例子:
// C# program to illustrate Dictionary
using System;
using System.Collections.Generic;
class GFG {
// Main Method
static public void Main()
{
// Creating a dictionary
// using Dictionary class
Dictionary My_dict =
new Dictionary();
// Adding key/value pairs in the Dictionary
// Using Add() method
My_dict.Add("a.01", "C");
My_dict.Add("a.02", "C++");
My_dict.Add("a.03", "C#");
foreach(KeyValuePair element in My_dict)
{
Console.WriteLine("Key:- {0} and Value:- {1}",
element.Key, element.Value);
}
}
}
输出:
Key:- a.01 and Value:- C
Key:- a.02 and Value:- C++
Key:- a.03 and Value:- C#
Hashtable 是基于键的哈希码排列的键/值对的集合。或者换句话说,哈希表用于创建使用哈希表进行存储的集合。它是在 System.Collections命名空间中定义的非泛型集合类型。在 Hashtable 中,key 对象必须是不可变的,只要它们在 Hashtable 中用作 key。
例子:
// C# program to illustrate a hashtable
using System;
using System.Collections;
class GFG {
// Main method
static public void Main()
{
// Create a hashtable
// Using Hashtable class
Hashtable my_hashtable = new Hashtable();
// Adding key/value pair in the hashtable
// Using Add() method
my_hashtable.Add("A1", "Welcome");
my_hashtable.Add("A2", "to");
my_hashtable.Add("A3", "GeeksforGeeks");
foreach(DictionaryEntry element in my_hashtable)
{
Console.WriteLine("Key:- {0} and Value:- {1} ",
element.Key, element.Value);
}
}
}
输出:
Key:- A3 and Value:- GeeksforGeeks
Key:- A2 and Value:- to
Key:- A1 and Value:- Welcome
哈希表与字典
Hashtable | Dictionary |
---|---|
A Hashtable is a non-generic collection. | A Dictionary is a generic collection. |
Hashtable is defined under System.Collections namespace. | Dictionary is defined under System.Collections.Generic namespace. |
In Hashtable, you can store key/value pairs of the same type or of the different type. | In Dictionary, you can store key/value pairs of same type. |
In Hashtable, there is no need to specify the type of the key and value. | In Dictionary, you must specify the type of key and value. |
The data retrieval is slower than Dictionary due to boxing/ unboxing. | The data retrieval is faster than Hashtable due to no boxing/ unboxing. |
In Hashtable, if you try to access a key that doesn’t present in the given Hashtable, then it will give null values. | In Dictionary, if you try to access a key that doesn’t present in the given Dictionary, then it will give error. |
It is thread safe. | It is also thread safe but only for public static members. |
It doesn’t maintain the order of stored values. | It always maintain the order of stored values. |