C#實現Hashtable中
根據鍵值對的值,然后進行刪除這一個鍵值對
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;
namespace Test1112
{
class Program
{
static void Main(string[] args)
{
Hashtable ht = new Hashtable();
ht.Add("1","張三");
ht.Add("2", "李四");
ht.Add("3", "王五");
ht.Add("4", "小明");
if(ht.ContainsValue("張三")){
Console.WriteLine("學生張三已經在集合中了!");
}else{
ht.Add("5","小剛");
}
ht.Remove("2");
foreach(string key in ht.Keys)
{
Console.WriteLine(key +":"+ht[key]);
}
Console.WriteLine("---------------------------------");
foreach(DictionaryEntry de in ht) //fileht為一個Hashtable實例
{
//Console.WriteLine("aaaaa :" + de.Key.GetType());//de.Key對應於keyvalue鍵值對key,System.String
//Console.WriteLine("bbbbbbbb :" + de.Value.GetType());//de.Key對應於keyvalue鍵值對value,System.String
string a = de.Value.ToString();
//Console.WriteLine(a);
string b = "張三";
//已經是
if(a.Equals(b))
{
//Console.WriteLine(de.Key.GetType());
object c = de.Key;//因為ht.Remove(object o)里面只能傳入object類型,所以這邊進行隱式轉換
ht.Remove(c);
break;//找到了直接讓循環結束
}
}
//顯示結果
Console.WriteLine("--------------------------------");
Console.WriteLine("最后的輸出結果為:");
foreach (string key in ht.Keys)
{
Console.WriteLine(key + ":" + ht[key]);
}
Console.Read();
}
}
}