C# Dictionary泛型集合

C# Dictionary泛型集合_第1张图片
重要方法的工程结构(控制台应用程序)+测试代码+运行结果
C# Dictionary泛型集合_第2张图片

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)
        {
            
             
            
            //1.添加
            titleNameDic.Add("师傅","唐三藏");
            titleNameDic.Add("大师兄","孙悟空");
            titleNameDic.Add("二师兄","猪八戒");
            titleNameDic.Add("沙师弟","沙悟净");
            titleNameDic.Add("白龙马","敖烈");

            
            //2.移除 
            titleNameDic.Remove("白龙马");//移除:remove(键)

            

            //3_1.访问(法一)
            Console.WriteLine("“师傅”对应的名字是:" + titleNameDic["师傅"]);

            

            //3_2.访问(法二)
            string s = string.Empty;
            titleNameDic.TryGetValue("大师兄", out s);
            Console.WriteLine("“大师兄”对应的名字是:" + s);

            Console.WriteLine();
            Console.WriteLine();
            Console.WriteLine();

            //4_1.据“键值对”遍历
            foreach (KeyValuePair<string, string> kvp in titleNameDic)
            {
                Console.WriteLine("通过键值对遍历集合,Key = {0}, Value = {1}", kvp.Key, kvp.Value);
            }
            Console.WriteLine();

            //4_2.据“键”遍历            
            foreach (string title in titleNameDic.Keys)
            {
                Console.WriteLine("键:"+title+"   "+"值:"+titleNameDic[title]);
            }
            Console.WriteLine();

            //4_3.据“值”遍历           
            foreach (string name in titleNameDic.Values)
            {
                Console.WriteLine( "值:" + name);
            }

            Console.WriteLine();
            Console.WriteLine();
            Console.WriteLine();

            //ContainsKey()、ContainsValue() —— 是否包含键、值
            Console.WriteLine("是否包含键“唐太宗”:"+titleNameDic.ContainsKey("唐太宗"));
            Console.WriteLine("是否包含值“沙悟净”:" + titleNameDic.ContainsValue("沙悟净"));

            Console.WriteLine();
            Console.WriteLine();
            Console.WriteLine();

            
            Console.WriteLine("清空后,查看集合内容:");

            //Clear()清空
            titleNameDic.Clear();
            foreach (KeyValuePair<string, string> kvp in titleNameDic)
            {
                Console.WriteLine("通过键值对遍历集合,Key = {0}, Value = {1}", kvp.Key, kvp.Value);
            }

            Console.ReadKey();

        }
    }
}

C# Dictionary泛型集合_第3张图片

你可能感兴趣的:(#,集合,C#,Dictionary,泛型集合)