博客园  :: 联系 :: 管理

【转】C#集合之Hashtable

Posted on 2011-02-24 09:27  独孤雁  阅读(635)  评论(0编辑  收藏  举报

1、HashTable定义

System.Collections. Hashtable类表示键/值对的集合,这些键/值对根据键的哈希代码进行组织, 每个元素都是一个存储在 DictionaryEntry 对象中的键/值对。键不能为 null,但值可以。

2.优点

1、通过Key快速查找。

2、Hashtable 是线程安全的。

3. Hashtable的构造器

构造器函数

注释

Public Hashtable ()

使用默认的初始容量(容量大小为0)、加载因子、哈希代码提供程序和比较器来初始化 Hashtable 类的新的空实例。

public Hashtable (IDictionary)

通过将指定字典中的元素复制到新的 Hashtable 对象中,初始化 Hashtable 类的一个新实例。新 Hashtable 对象的初始容量等于复制的元素数,并且使用默认的加载因子、哈希代码提供程序和比较器。

public Hashtable (Int32)

使用指定的初始容量、默认加载因子、默认哈希代码提供程序和默认比较器来初始化 Hashtable 类的新的空实例。

4、Hashtable的属性

属性名

注释

Count

获取包含在 Hashtable 中的键/值对的数目。

IsFixedSize

获取一个值,该值指示 Hashtable 是否具有固定大小。

IsReadOnly

获取一个值,该值指示 Hashtable 是否为只读。

Keys

获取包含 Hashtable 中的键的 ICollection

Values

获取包含 Hashtable 中的值的 ICollection。

5. Hashtable的方法

方法名

注释

Void Add(object key,object value)

将带有指定键和值的元素添加到 Hashtable 中。

Void Clear()

从 Hashtable 中移除所有元素。

Bool Contains(object key)

确定 Hashtable 是否包含特定键。

Bool ContainsKey(object key)

确定 Hashtable 是否包含特定键。

Bool ContainsValue(object value)

确定 Hashtable 是否包含特定值。

Void Remove(object key)

从 Hashtable 中移除带有指定键的元素。

Void InsertRange(int index,Icollection collec)

用于从指定位置开始添加一批元素,列表后面的元素依次往后移动

Clone()

创建 Hashtable 的浅表副本。

GetObjectData()

实现 ISerializable 接口,并返回序列化 Hashtable 所需的数据。

6、Hashtable的使用示例

代码
public class Program
{
public static void Main(string[] args)
{
//创建一个HashTable
Hashtable openWith = new Hashtable();

//为HashTable添加元素,不能有重复的key,但可以有重复的值
openWith.Add("txt", "notepad.exe");
openWith.Add(
"bmp", "paint.exe");
openWith.Add(
"dib", "paint.exe");
openWith.Add(
"rtf", "wordpad.exe");



//添加重复的key,会抛出异常
try
{
openWith.Add(
"txt", "winword.exe");
}
catch
{
Console.WriteLine(
"An element with Key = \"txt\" already exists.");
}

//通过key获得值
Console.WriteLine("For key = \"rtf\", value = {0}.", openWith["rtf"]);

//重新赋值
openWith["rtf"] = "winword.exe";
Console.WriteLine(
"For key = \"rtf\", value = {0}.", openWith["rtf"]);

//以赋值的方式,创建一个新元素
openWith["doc"] = "winword.exe";

//如果HashTable中不包含该元素,将抛出异常(经测试这里不抛出异常)
//原因(如果未找到指定的键,尝试获取它将返回 空引用(在 Visual Basic 中为 Nothing),尝试设置它将使用指定的键创建新元素。 )
try
{
Console.WriteLine(
"For key = \"tif\", value = {0}.", openWith["tif"]);
}
catch
{
Console.WriteLine(
"Key = \"tif\" is not found.");
}

//判断是否包含特定的key
if (!openWith.ContainsKey("ht"))
{
openWith.Add(
"ht", "hypertrm.exe");
Console.WriteLine(
"Value added for key = \"ht\": {0}", openWith["ht"]);
}

//遍历HashTable
Console.WriteLine();
foreach (DictionaryEntry de in openWith)
{
Console.WriteLine(
"Key = {0}, Value = {1}", de.Key, de.Value);
}

// 获取HashTable中值的集合
ICollection valueColl = openWith.Values;


Console.WriteLine();
foreach (string s in valueColl)
{
Console.WriteLine(
"Value = {0}", s);
}

// 获取HashTable中键的集合
ICollection keyColl = openWith.Keys;


Console.WriteLine();
foreach (string s in keyColl)
{
Console.WriteLine(
"Key = {0}", s);
}


Console.WriteLine(
"\nRemove(\"doc\")");
//移除指定的元素
openWith.Remove("doc");

if (!openWith.ContainsKey("doc"))
{
Console.WriteLine(
"Key \"doc\" is not found.");
}


Hashtable mySourceHT
= new Hashtable();
mySourceHT.Add(
"A", "valueA");
mySourceHT.Add(
"B", "valueB");

// 创建一个字符串数组
String[] myTargetArray = new String[15];
myTargetArray[
0] = "The";
myTargetArray[
1] = "quick";
myTargetArray[
2] = "brown";
myTargetArray[
3] = "fox";
myTargetArray[
4] = "jumped";
myTargetArray[
5] = "over";
myTargetArray[
6] = "the";
myTargetArray[
7] = "lazy";
myTargetArray[
8] = "dog";

// 遍历数组的值
Console.WriteLine("The target Array contains the following before:");
PrintValues(myTargetArray,
' ');

//将hashtable中的key复制到数组中
Console.WriteLine("After copying the keys, starting at index 6:");
mySourceHT.Keys.CopyTo(myTargetArray,
6);


PrintValues(myTargetArray,
' ');

//将hashtable中的Value复制到数组中
Console.WriteLine("After copying the values, starting at index 6:");
mySourceHT.Values.CopyTo(myTargetArray,
6);

PrintValues(myTargetArray,
' ');

Console.Read();
}

//遍历数据方法
public static void PrintValues(String[] myArr, char mySeparator)
{
for (int i = 0; i < myArr.Length; i++)
Console.Write(
"{0}{1}", mySeparator, myArr[i]);
Console.WriteLine();
}

}

7、Hashtable遍历方法

方法一

 foreach (System.Collections.DictionaryEntry objDE in objHasTab)
{
    Console.WriteLine(objDE.Key.ToString());
    Console.WriteLine(objDE.Value.ToString());
}

 

方法二

System.Collections.IDictionaryEnumerator enumerator = objHashTablet.GetEnumerator();
while (enumerator.MoveNext())
{
    Console.WriteLine(enumerator.Key);         // Hashtable关健字
    Console.WriteLine

}

8、Hashtable排序

//把ht的键对象全部复制到ArrayList中

 ArrayList al = new ArrayList(ht.Keys);

 /*ht.Keys返回ht中所有键对象构成的集合,把该集合传递给ArrayList构造方法则得到一个包

*所有键对象的动态数组

*/

  al.Sort();//从小到大排列

  //排序完成输出

   for (int i = 0; i < al.Count;i++ )

   {

          object e=al[i];

          object temp = (object)ht[e];//键作为索引器来获得对应的值对象

           Console.WriteLine(temp.tostring());

}