Dictionary可以取代Hashtable了;
有一種新的遍歷方式
foreach(KeyValuePair kv in dic){}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Dictionary字典
{
class Program
{
static void Main(string[] args)
{
Dictionary dic = new Dictionary();
dic.Add(1, "荊轲");
dic.Add(2, "聶政");
dic.Add(3, "專諸");
dic.Add(4, "要離");
foreach (int item in dic.Keys)
{
Console.WriteLine("{0}對應的值為{1}",item,dic[item]);
}
foreach(KeyValuePair pair in dic)
{
Console.WriteLine("{0}對應的值為{1}",pair.Key,pair.Value);
}
Console.ReadKey();
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Dictionary檢測字母出現次數
{
class Program
{
static void Main(string[] args)
{
//檢測字符串"Welcome To China"裡面每個字符出現的次數;
Dictionary dic = new Dictionary();
string str = "Welcome To China";
for (int i = 0; i < str.Length; i++)
{
if (str[i]==' ')
{
continue;
}
if (dic.ContainsKey((str.ToLower())[i]))
{
dic[(str.ToLower())[i]]++;
}
else
{
dic[(str.ToLower())[i]] = 1;
}
}
foreach (KeyValuePair item in dic)
{
Console.WriteLine("{0}出現過{1}次",item.Key,item.Value);
}
Console.ReadKey();
}
}
}