重要方法的工程结构(控制台应用程序)+测试代码+运行结果:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Dictionary泛型集合
{
class Program
{
static Dictionary<string, string> titleNameDic = new Dictionary<string,string>();
static void Main(string[] args)
{
titleNameDic.Add("师傅","唐三藏");
titleNameDic.Add("大师兄","孙悟空");
titleNameDic.Add("二师兄","猪八戒");
titleNameDic.Add("沙师弟","沙悟净");
titleNameDic.Add("白龙马","敖烈");
titleNameDic.Remove("白龙马");
Console.WriteLine("“师傅”对应的名字是:" + titleNameDic["师傅"]);
string s = string.Empty;
titleNameDic.TryGetValue("大师兄", out s);
Console.WriteLine("“大师兄”对应的名字是:" + s);
Console.WriteLine();
Console.WriteLine();
Console.WriteLine();
foreach (KeyValuePair<string, string> kvp in titleNameDic)
{
Console.WriteLine("通过键值对遍历集合,Key = {0}, Value = {1}", kvp.Key, kvp.Value);
}
Console.WriteLine();
foreach (string title in titleNameDic.Keys)
{
Console.WriteLine("键:"+title+" "+"值:"+titleNameDic[title]);
}
Console.WriteLine();
foreach (string name in titleNameDic.Values)
{
Console.WriteLine( "值:" + name);
}
Console.WriteLine();
Console.WriteLine();
Console.WriteLine();
Console.WriteLine("是否包含键“唐太宗”:"+titleNameDic.ContainsKey("唐太宗"));
Console.WriteLine("是否包含值“沙悟净”:" + titleNameDic.ContainsValue("沙悟净"));
Console.WriteLine();
Console.WriteLine();
Console.WriteLine();
Console.WriteLine("清空后,查看集合内容:");
titleNameDic.Clear();
foreach (KeyValuePair<string, string> kvp in titleNameDic)
{
Console.WriteLine("通过键值对遍历集合,Key = {0}, Value = {1}", kvp.Key, kvp.Value);
}
Console.ReadKey();
}
}
}
|