它的样式是Dictionary<TKey,TValue> Class,TKey表示字典中键的类型,TValue表示字典中值的类型,任何键都必须是唯一的。
以下是关于官方示例的引用
static void Main(string[] args)
{
Dictionary<string, string> openWith = new Dictionary<string, string>();
// Add some elements to the dictionary. There are no
// duplicate keys, but some of the values are duplicates.
openWith.Add("txt", "notepad.exe");
openWith.Add("bmp", "paint.exe");
openWith.Add("dib", "paint.exe");
openWith.Add("rtf", "wordpad.exe");
// The Add method throws an exception if the new key is
// already in the dictionary.
try
{
openWith.Add("txt", "winword.exe");
}
catch (ArgumentException)
{
Console.WriteLine("An element with Key = \"txt\" already exists.");
}
Console.WriteLine("For key = \"rtf\", value = {0}.",openWith["rtf"]);
if (!openWith.ContainsKey("ht"))//验证键值是否存在
{
openWith.Add("ht", "hypertrm.exe");
Console.WriteLine("Value added for key = \"ht\": {0}", openWith["ht"]);
}
// 仅仅得到值的集合
Dictionary<string, string>.ValueCollection valueColl = openWith.Values;
Console.WriteLine();
foreach (string s in valueColl)
{
Console.WriteLine("Value = {0}", s);
}
//仅仅得到键的集合
Dictionary<string, string>.KeyCollection keyColl = openWith.Keys;
Console.WriteLine();
foreach (string s in keyColl)
{
Console.WriteLine("Key = {0}", s);
}
}
利用这个方法来解决字符串中某个字符出现的次数特别简单
class Program
{
static Dictionary< string, int> dic = new Dictionary<string, int>();
static void Main(string[] args)
{
int i = 6;
while(i>0)
{
Insert(Console.ReadLine());
i--;
}
foreach (var item in dic)
{
if (item.Value == 1)
{
Console.WriteLine("第{0}值出现了一次", item.Key);
}
}
}
public static void Insert(string c)
{
if (dic.ContainsKey(c))//ContainsKey包含则为真
dic[c]++;
else
dic[c] = 1;
}
}