Dictionary 小知识

Dictionary<string, string>是一个泛型

他本身有集合的功能有时候可以把它看成数组

他的结构是这样的:Dictionary<[key], [value]>

他的特点是存入对象是需要与[key]值一一对应的存入该泛型

通过某一个一定的[key]去找到对应的值

举个例子:

//实例化对象

Dictionary < int, string > dic = new Dictionary < int, string > ();
//对象打点添加
dic.Add(1, "one");
dic.Add(2, "two");
dic.Add(3, "one");
//提取元素的方法
string a = dic[1];
string b = dic[2];
string c = dic[3];
//1、2、3是键,分别对应“one”“two”“one”
//上面代码中分别把值赋给了a,b,c
//注意,键相当于找到对应值的唯一标识,所以不能重复
//但是值可以重复
static void Main(string[] args)
{
    #region List
    List < string > list = new List < string > ();
    List < int > li = new List < int > ();
    li.Sum();
    // li.Average();
    // li.Skip();
    // hashTable 的升级版本 Dictionary
    // Generic 泛型
    Dictionary < string, int > dic = new Dictionary < string, int > ();
    // 键是string 值是int类型
    dic.Add("zxc", 123);
    dic.Add("asd", 456);
    Console.WriteLine(dic["zxc"]); //这里的键也不能重复
    // 遍历“键”
    Console.WriteLine("========遍历“键”=================");
    foreach(string item in dic.Keys)
        {
            Console.WriteLine(item);
        }
        // 遍历“值”
    Console.WriteLine("========遍历“值”=================");
    foreach(var item in dic.Values)
    {
        Console.WriteLine(item);
    }
    Console.WriteLine("========键值同时遍历=================");
    foreach(KeyValuePair < string, int > item in dic)
    {
        Console.WriteLine("键:{0} 值:{1}", item.Key, item.Value);
    }
    Console.ReadKey();
    #endregion
    //string str = "1a 2b 3c 4d 5e";
    //string[] parts = str.Split(' ');
    //foreach (var item in parts)
    //{
    // Console.WriteLine(item);
    //}
    //Dictionary<char, char> dic = new Dictionary<char, char>();
    //for (int i = 0; i < parts.Length; i++)
    //{
    // dic.Add(parts[i][0],parts[i][1]);
    //}
    //string num = Console.ReadLine();
    //StringBuilder sb = new StringBuilder();
    //for (int i = 0; i < num.Length; i++)
    //{
    // sb.Append(dic[num[i]]);
    //}
    //Console.WriteLine(sb.ToString());
    //Console.ReadKey();
}
原文地址:https://www.cnblogs.com/ZkbFighting/p/7732959.html