求一个使用哈希的例子

s393658806 2009-08-02 03:22:35

求一个使用哈希的例子
...全文
89 4 打赏 收藏 转发到动态 举报
写回复
用AI写文章
4 条回复
切换为时间正序
请发表友善的回复…
发表回复
让爱延续 2009-08-03
  • 打赏
  • 举报
回复
都这么详细啦,算了我不多说了,顶。
spmzfz 2009-08-03
  • 打赏
  • 举报
回复

//Hashtable 表示键/值对的集合,这些键/值对根据键的哈希代码进行组织。
Hashtable ht = new Hashtable();
ht.Add(1, null);
ht.Add(2, "2");
ht.Add(3, "3");
ht.Add(4, "4");

Console.WriteLine("\nht.ContainsKey(3) = {0}\tht.ContainsValue(\"3\") = {1}", ht.ContainsKey(3), ht.ContainsValue("3"));
//System.Collections.IEnumerator ien = ht.GetEnumerator();

//ht.Remove(1); //移除键
//ht.Clear(); //清除所有的键

//1
foreach (int item in ht.Keys )
{
Console.WriteLine("key = {0}\t value = {1}", item, ht[item]);
}

//2
foreach (DictionaryEntry item in ht) //DictionaryEntry 定义可设置或检索的字典键/值对。
{
Console.WriteLine("{0} {1}", item.Key, item.Value);
}

Console.WriteLine("-------------------------------------------------");
ICollection valuecoll = ht.Values; //ICollection 定义所有非泛型集合的大小、枚举数和同步方法。
Console.WriteLine("valuecoll.Count = {0}", valuecoll.Count.ToString()); //valuecoll.Count = 4

foreach (string item in valuecoll)
{
Console.WriteLine("value = {0}", item);
}

Console.WriteLine();
ICollection keycoll = ht.Keys;
foreach (int item in keycoll )
{
Console.WriteLine("key = {0}", item);
}
Console.WriteLine("-------------------------------------------------");

wuyq11 2009-08-02
  • 打赏
  • 举报
回复
Hashtable table = new Hashtable();
table.Add(1, "A");
table.Add(2, "B");
table.Add(3, "C");

table.Remove(2);
foreach (Object o in table.Keys) {
Console.WriteLine(o.ToString());
}
foreach (DictionaryEntry d in table) {
Console.WriteLine ("{0}\t{1}", d.Key, d.Value);
}



qqiuzaihui 2009-08-02
  • 打赏
  • 举报
回复
using System;
using System.Collections; //使用Hashtable时,必须引入这个命名空间

class hashtable
{
public static void Main()
{
Hashtable ht=new Hashtable(); //创建一个Hashtable实例
ht.Add("E","eeee"); //添加key/value键值对
ht.Add("A","aaaa");
ht.Add("C","cccc");
ht.Add("B","bbbb");

//遍历哈希表需要用到 DictionaryEntry Object
foreach(DictionaryEntry de in ht) //ht为一个Hashtable实例
{
Console.Write(de.Key + " "); //de.Key对应于key/value键值对key
Console.WriteLine(de.Value); //de.Key对应于key/value键值对value
}

//对哈希表进行排序
ArrayList akeys=new ArrayList(ht.Keys);
akeys.Sort(); //按字母顺序进行排序
foreach (string skey in akeys)
{
Console.Write(skey + ":");
Console.WriteLine(ht[skey]); //排序后输出
}

string s=(string)ht["A"];
Console.WriteLine(s);

if(ht.Contains("E")) //判断哈希表是否包含特定键,其返回值为true或false
Console.WriteLine("the E key:exist");

ht.Remove("C"); //移除一个key/value键值对
Console.WriteLine(ht["A"]); //此处输出a
ht.Clear(); //移除所有元素
Console.WriteLine(ht["A"]); //此处将不会有任何输出

Console.ReadKey();
}
}

110,538

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • Web++
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧