版权声明:盗版必究 https://blog.csdn.net/jinxiul5/article/details/81981997
Dictionray(字典)
什么是字典:
字典是一种数组结构隶属于集合,字典按照字面的意思理解就是我们常用的字典,我们如果要查字典首先要按拼音进行,或者按照笔画进行,在C#中也是这样,C#中Dictionary 要查找,必须要有Key(键),Key呢在Dictionary中就相当于字典的拼音和笔画,而我们要查找的东西就是Value (值),这就是Dictionary;
特点:
Dictionary是泛型也就是说我们的Key 和Value 可是是任何类型的,根据自己的需要进行规定我们字典键值对的类型。
1.字典中的元素是无序的,也就是说我们不能通过下标获取值。
2.字典中的Key是唯一的,不能够重复。
3.字典中的元素都是成对出现的,不会出现单一值或者单一健的情况
4.字典也是引用类型,必须手动开辟空间。
Dictionary中的方法,和使用方法:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Collections;
namespace ConsoleApp1
{
class Program
{
static void Main(string[] args)
{
//创建一个字典
Dictionary<string, int> _dic = new Dictionary<string, int> ( );
//向字典中添加(Key ,Value)键值对
_dic.Add ("小三", 22);
_dic.Add ("小四", 26);
_dic.Add ("小五", 24);
_dic.Add ("小六", 28);
//根据键获取字典中的值
int a1 =_dic["小五"];
//该方法用于不确定字典中是否存在指定的Key,如果不存在就返回false,并且v1的值为null ,如果存在就返回true,并且把该Key所对应的Value返回给v1.
int v1;
bool b3 =_dic.TryGetValue ( "小三",out v1);
//获取字典中键值对的数量_dic.Count ( )
int _count =_dic.Count ( );
//查看当前字典中是否包含指定的Key
bool b2 = _dic.ContainsKey ("小三");
//查看当前字典中是否包含指定的Value
bool b1 = _dic.ContainsValue (28);
//根据键删除键值对
_dic.Remove ("小五" );
//清空字典
_dic.Clear ( );
Console.ReadKey ( );
}
}
}