标签:c# dictionary 字典 哈希
Dictionary可以取代Hashtable了;
有一种新的遍历方式
foreach(KeyValuePair <int,string> 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<int, string> dic = new Dictionary<int, string>();
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<int,string> 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<char, int> dic = new Dictionary<char, int>();
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<char,int> item in dic)
{
Console.WriteLine("{0}出现过{1}次",item.Key,item.Value);
}
Console.ReadKey();
}
}
}
标签:c# dictionary 字典 哈希
原文地址:http://blog.csdn.net/zhzz2012/article/details/46012139