編寫一個控制台程序,
創建哈希集合,內含部分國家的名稱和首都,
提示用戶輸入一個國家名稱,則在哈希集合中查找該國首都名稱並輸出。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;
namespace hashtable
{
class Program
{
static void Main(string[] args)
{
Hashtable hst = new Hashtable();
hst.Add("China", "Beijing");
hst.Add("England", "London");
hst.Add("Japan", "Tokyo");
string a;
a = Console.ReadLine();
Console.WriteLine(hst[a]);
Console.Read();
}
}
}
輸入學號和姓名,對不存在的學號加到hashtable類的實例中,
對存在學號給出提示。結束輸入後,輸出學號為奇數的所有學生。
方案1:使用哈希表的泛型Dictionary<>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;
namespace hashtable
{
class Program
{
static void Main(string[] args)
{
Dictionary <int, string> hst = new Dictionary <int, string>();
string name;
int sid;
string temp;
while (true)
{
Console.Write("輸入學生姓名: ");
name = Console.ReadLine();
Console.Write("輸入學生學號: ");
sid = Convert.ToInt32(Console.ReadLine());
if (hst.ContainsKey(sid))
{
Console.WriteLine("該值已存在,是否繼續添加?(Y/N)");
temp = Console.ReadLine();
if (temp == "Y" || temp == "y")
continue;
else
break;
}
else
{
hst.Add(sid, name);
Console.WriteLine("添加成功,是否繼續添加?(Y/N)");
temp = Console.ReadLine();
if (temp == "Y" || temp == "y")
continue;
else
break;
}
}//end of input
foreach (var item in hst)
{
if (item.Key % 2 == 1)
{
Console.WriteLine("{0}, {1}", item.Value, item.Key);
}
}
Console.Read();
}
}
}
方案二:使用哈希表Hastable()
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;
namespace hashtable
{
class Program
{
static void Main(string[] args)
{
Hashtable hst = new Hashtable();
//hst[key] = value;
string name;
int sid;
string temp;
while (true)
{
Console.Write("輸入學生姓名: ");
name = Console.ReadLine();
Console.Write("輸入學生學號: ");
sid = Convert.ToInt32(Console.ReadLine());
if (hst[sid] != null)
{
Console.WriteLine("該值已存在,是否繼續添加?(Y/N)");
temp = Console.ReadLine();
if (temp == "Y" || temp == "y")
continue;
else
break;
}
else
{
hst.Add(sid, name);
Console.WriteLine("添加成功,是否繼續添加?(Y/N)");
temp = Console.ReadLine();
if (temp == "Y" || temp == "y")
continue;
else
break;
}
}//end of input
int tmp;
foreach (DictionaryEntry item in hst)
{
tmp = (int)item.Key;
if (tmp % 2 == 1)
Console.WriteLine("{0}, {1}", item.Value, item.Key);
}
Console.Read();
}
}
}