【C#】Dictionary

来源:互联网 发布:c语言中stdlib 编辑:程序博客网 时间:2024/05/17 03:29

原文链接:https://jingyan.baidu.com/article/9989c7460ab872f648ecfeed.html

基本认识

  在C#中,Dictionary提供快速的基于键值的元素查找。他的结构是这样的:Dictionary<[key], [value]> ,当你有很多元素的时候可以使用它。它包含在System.Collections.Generic名空间中。在使用前,你必须声明它的键类型和值类型。

使用须知

1、 要使用Dictionary集合,需要导入C#泛型命名空间 System.Collections.Generic(程序集:mscorlib)。
2、 Dictionary的描述

  • 从一组键(Key)到一组值(Value)的映射,每一个添加项都是由一个值及其相关连的键组成。
  • 任何键都必须是唯一的。
  • 键不能为空引用null(VB中的Nothing),若值为引用类型,则可以为空值。
  • Key和Value可以是任何类型(string,int,custom class 等)。

实例应用

Dictionary常规用法:以 key 的类型为 int , value的类型为string 为例。

private void Dictionay_Click(object sender, EventArgs e){    //1、创建及初始化    Dictionary<int, string> myDictionary = new Dictionary<int, string>();    // 2、添加元素    myDictionary.Add(1, "C#");    myDictionary.Add(2, "C++");    myDictionary.Add(3, "ASP.NET");    myDictionary.Add(4, "MVC");    //3、通过Key查找元素    if (myDictionary.ContainsKey(1))    {        MessageBox.Show("Key:" + 1 + "\n" + "Value:" + myDictionary[1]);    }    //4、通过KeyValuePair遍历元素    foreach (KeyValuePair<int, string> kvp in myDictionary)    {        MessageBox.Show("Key:" + kvp.Key + "\n" + "Value:" + kvp.Value);    }    //5、仅遍历键 Keys 属性    Dictionary<int, string>.KeyCollection keyCol = myDictionary.Keys;    foreach (int key in keyCol)    {        MessageBox.Show("Key:" + key);    }    //6、仅遍历值 Valus属性    Dictionary<int, string>.ValueCollection valueCol = myDictionary.Values;    foreach (string value in valueCol)    {        MessageBox.Show("Value:" + value);    }    //7、通过Remove方法移除指定的键值    myDictionary.Remove(1);    if (myDictionary.ContainsKey(1))    {        MessageBox.Show("Key:" + 1 + "\n" + "Value:" + myDictionary[1]);    }    else    {        MessageBox.Show("不存在 Key : 1");    }}

其它常见属性和方法的说明

属性/方法 说明 Comparer 获取用于确定字典中的键是否相等的IEqualityComparer。 Count 获取包含在 Dictionary中的键/值对的数目。 Item 获取或设置与指定的键相关联的值。 Clear 从 Dictionary中移除所有的键和值。 ContainsKey 确定 Dictionary是否包含指定的键。 ContainsValue 确定 Dictionary是否包含特定值。 GetEnumerator 返回循环访问 Dictionary的枚举数。 GetType 获取当前实例的 Type。 (从 Object 继承。) Remove 从 Dictionary中移除所指定的键的值。 ToString 返回表示当前 Object的 String。 (从 Object 继承。) TryGetValue 获取与指定的键相关联的值。
原创粉丝点击