C#中Dictionary的用法

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

     泛型最常见的用途是泛型集合,命名空间System.Collections.Generic 中包含了一些基于泛型的集合类,使用泛型集合类可以提供更高的类型安全性,还有更高的性能,避免了非泛型集合的重复的装箱和拆箱。

下面是常用的泛型集合类:

List<T>、DIctionary<T,V>、Queue<T>、Stack<T>、SortedList<T>

下面介绍 DIctionary<T,V> 的用法:

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

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

3、常用用法:以 key 的类型为 int , value的类型为string 为例

创建及初始化

 
C# 代码   复制
 
Dictionary<int, string> myDictionary = new Dictionary<int, string>();

添加元素

    C# 代码   复制

    
    myDictionary.Add(1,"C#");
   myDictionary.Add(2,"C++");
   myDictionary.Add(3,"ASP.NET");
   myDictionary.Add(4,"MVC");

通过Key查找元素

    C# 代码   复制


if(myDictionary.ContainsKey(1))
{
  Console.WriteLine("Key:{0},Value:{1}", "1", myDictionary[1]);
}

通过KeyValuePair遍历元素 

    C# 代码   复制


foreach (KeyValuePair<int,string> kvp in myDictionary)
{
  Console.WriteLine("Key = {0}, Value = {1}",kvp.Key, kvp.Value);
}

仅遍历键 Keys 属性

 

   C# 代码   复制

Dictionary<int, string>.KeyCollection keyCol = myDictionary.Keys;
foreach (int key in keyCol)
{
  Console.WriteLine("Key = {0}", key);
}

仅遍历值 Valus属性

 

  C# 代码    复制

Dictionary<int, string>.ValueCollection valueCol = myDictionary.Values;
foreach (string value in valueCol)
{
  Console.WriteLine("Value = {0}", value);
}

通过Remove方法移除指定的键值

 
C# 代码   复制
   myDictionary.Remove(1);
  if (myDictionary.ContainsKey(1))
  {
    Console.WriteLine("Key:{0},Value:{1}", "1", myDictionary[1]);
  }
  else
  {
    Console.WriteLine("不存在 Key : 1");
   }

4、其它常见属性和方法的说明:
   Comparer
   获取用于确定字典中的键是否相等的 IEqualityComparer。

   Count
   获取包含在 Dictionary中的键/值对的数目。

   Item
   获取或设置与指定的键相关联的值。

   Keys
   获取包含 Dictionary中的键的集合。

   Values
   获取包含 Dictionary中的值的集合。

   Add
   将指定的键和值添加到字典中。

   Clear
   从 Dictionary中移除所有的键和值。

   ContainsKey
   确定 Dictionary是否包含指定的键。

   ContainsValue
   确定 Dictionary是否包含特定值。

   Equals
   已重载。 确定两个 Object 实例是否相等。 (从 Object 继承。)

   GetEnumerator
   返回循环访问 Dictionary的枚举数。

   GetHashCode
   用作特定类型的哈希函数。GetHashCode 适合在哈希算法和数据结构(如哈希表)中使用。 (从 Object 继承。)

   GetObjectData
   实现 System.Runtime.Serialization.ISerializable 接口,并返回序列化 Dictionary实例所需的数据。

   GetType
   获取当前实例的 Type。 (从 Object 继承。)

   OnDeserialization
   实现 System.Runtime.Serialization.ISerializable接口,并在完成反序列化之后引发反序列化事件。

   ReferenceEquals
   确定指定的 Object实例是否是相同的实例。 (从 Object 继承。)

   Remove
   从 Dictionary中移除所指定的键的值。

   ToString
   返回表示当前 Object的 String。 (从 Object 继承。)

   TryGetValue
   获取与指定的键相关联的值。


评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值