当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


C# Dictionary用法及代码示例


Dictionary<TKey, TValue> 类C# 中是键和值的集合。它是 System.Collections.Generic 命名空间中的通用集合类。这字典<TKey, TValue>泛型类提供从一组键到一组值的映射。字典中的每个添加都包含一个值及其关联的键。使用键检索值非常快,接近 O(1),因为 Dictionary 类是作为哈希表实现的。中的每个键字典<TKey, TValue>根据字典的相等比较器,它必须是唯一的。

注意:键不能为空,但值可以为空(如果值类型为空)T值是一个引用类型。

参数:

  • 钥匙:表示字典中键的类型。
  • T值:表示字典中值的类型。

由于 Dictionary<TKey, TValue> 是键和值的集合,因此元素类型不是键的类型或值的类型。相反,元素类型是键类型和值类型的 KeyValuePair <TKey, TValue>。

Constructors

构造函数 说明
字典<TKey, TValue>() 初始化 Dictionary<TKey, TValue> 类的新实例,该实例为空、具有默认初始容量,并对键类型使用默认相等比较器。
字典<TKey,TValue>(IDictionary<TKey,TValue>) 初始化 Dictionary<TKey, TValue> 类的新实例,其中包含从指定 IDictionary<TKey, TValue> 复制的元素,并使用键类型的默认相等比较器。
字典<TKey,TValue>(IDictionary<TKey,TValue>, IEqualityComparer<TKey>) 初始化 Dictionary<TKey,TValue> 类的新实例,其中包含从指定 IDictionary<TKey,TValue> 复制的元素并使用指定的 IEqualityComparer<T>。
字典<TKey,TValue>(IEqualityComparer<TKey>) 初始化 Dictionary<TKey,TValue> 类的新实例,该实例为空、具有默认初始容量并使用指定的 IEqualityComparer<T>。
字典<TKey,TValue>(Int32) 初始化 Dictionary 类的新实例,该实例为空、具有指定的初始容量并使用键类型的默认相等比较器。
字典<TKey,TValue>(Int32, IEqualityComparer<TKey>) 初始化 Dictionary<TKey,TValue> 类的新实例,该实例为空、具有指定的初始容量并使用指定的 IEqualityComparer<T>。
字典<TKey,TValue>(SerializationInfo, StreamingContext) 使用序列化数据初始化 Dictionary<TKey,TValue> 类的新实例。

例子:

C#


// C# code to create a Dictionary
using System;
using System.Collections.Generic;
class GFG {
    // Driver code
    public static void Main()
    {
        // Create a new dictionary of
        // strings, with string keys.
        Dictionary<string, string> myDict = 
          new Dictionary<string, string>();
        // Adding key/value pairs in myDict
        myDict.Add("1", "C");
        myDict.Add("2", "C++");
        myDict.Add("3", "Java");
        myDict.Add("4", "Python");
        myDict.Add("5", "C#");
        myDict.Add("6", "HTML");
        // To get count of key/value pairs in myDict
        Console.WriteLine("Total key/value pairs"+
              " in myDict are : " + myDict.Count);
        // Displaying the key/value pairs in myDict
        Console.WriteLine("\nThe key/value pairs"+
                           " in myDict are : ");
        foreach(KeyValuePair<string, string> kvp in myDict)
        {
            Console.WriteLine("Key = {0}, Value = {1}",
                              kvp.Key, kvp.Value);
        }
    }
}
输出:
Total key/value pairs in myDict are : 6

The key/value pairs in myDict are : 
Key = 1, Value = C
Key = 2, Value = C++
Key = 3, Value = Java
Key = 4, Value = Python
Key = 5, Value = C#
Key = 6, Value = HTML

Properties

特性 说明
Comparer 获取用于确定字典键相等性的 IEqualityComparer<TKey, TValue>。
Dictionary.Count 获取 Dictionary<TKey, TValue> 中包含的键/值对的数量。
Dictionary.Item[] 获取或设置与指定键关联的值。
Dictionary.Keys 获取包含 Dictionary<TKey, TValue> 中的键的集合。
Dictionary.Values 获取包含 Dictionary<TKey, TValue> 中的值的集合。

示例 1:

C#


// C# code to get the keys 
// in the Dictionary
using System;
using System.Collections.Generic;
class GFG {
    // Driver code
    public static void Main()
    {
        // Create a new dictionary of
        // strings, with string keys.
        Dictionary<string, string> myDict = 
          new Dictionary<string, string>();
        // Adding key/value pairs in myDict
        myDict.Add("1", "C");
        myDict.Add("2", "C++");
        myDict.Add("3", "Java");
        myDict.Add("4", "Python");
        myDict.Add("5", "C#");
        myDict.Add("6", "HTML");
        // To get count of key/value pairs in myDict
        Console.WriteLine("Total key/value pairs"+
              " in myDict are : " + myDict.Count);
        // To get the keys alone, use the Keys property.
        Dictionary<string, string>.KeyCollection keyColl = 
                                              myDict.Keys;
        // The elements of the KeyCollection
        // are strongly typed with the type 
        // that was specified for dictionary keys.
        foreach(string s in keyColl)
        {
            Console.WriteLine("Key = {0}", s);
        }
    }
}
输出:
Total key/value pairs in myDict are : 6
Key = 1
Key = 2
Key = 3
Key = 4
Key = 5
Key = 6

示例 2:

C#


// C# code to get the values
// in the Dictionary
using System;
using System.Collections.Generic;
class GFG {
    // Driver code
    public static void Main()
    {
        // Create a new dictionary of
        // strings, with string keys.
        Dictionary<string, string> myDict = 
           new Dictionary<string, string>();
        // Adding key/value pairs in myDict
        myDict.Add("1", "C");
        myDict.Add("2", "C++");
        myDict.Add("3", "Java");
        myDict.Add("4", "Python");
        myDict.Add("5", "C#");
        myDict.Add("6", "HTML");
        // To get count of key/value pairs in myDict
        Console.WriteLine("Total key/value pairs"+
              " in myDict are : " + myDict.Count);
        // To get the values alone, use the Values property.
        Dictionary<string, string>.ValueCollection valueColl = 
                                                myDict.Values;
        // The elements of the ValueCollection 
        // are strongly typed with the type 
        // that was specified for dictionary values.
        foreach(string s in valueColl)
        {
            Console.WriteLine("Value = {0}", s);
        }
    }
}
输出:
Total key/value pairs in myDict are : 6
Value = C
Value = C++
Value = Java
Value = Python
Value = C#
Value = HTML

Methods

方法 说明
Dictionary.Add() 将指定的键和值添加到字典中。
Dictionary.Clear 从 Dictionary<TKey, TValue> 中删除所有键和值。
Dictionary.ContainsKey() 确定 Dictionary<TKey, TValue> 是否包含指定的键。
Dictionary.ContainsValue() 确定 Dictionary<TKey, TValue> 是否包含特定值。
Equals(Object) 确定指定对象是否等于当前对象。
GetEnumerator() 返回一个迭代 Dictionary<TKey, TValue> 的枚举器。
GetHashCode() 用作默认的哈希函数。
GetObjectData(SerializationInfo, StreamingContext) 实现 ISerialized 接口并返回序列化 Dictionary<TKey,TValue> 实例所需的数据。
GetType() 获取当前实例的类型。
MemberwiseClone() 创建当前对象的浅拷贝。
OnDeserialization(Object) 实现 ISerialized 接口并在反序列化完成时引发反序列化事件。
Dictionary.Remove 从 Dictionary<TKey, TValue> 中删除具有指定键的值。
ToString() 返回表示当前对象的字符串。
TryGetValue(TKey, TValue) 获取与指定键关联的值。

示例 1:

C#


// C# code to remove all entries
//  from Dictionary
using System;
using System.Collections.Generic;
class GFG {
    // Driver code
    public static void Main()
    {
        // Create a new dictionary of 
        // strings, with string keys.
        Dictionary<string, string> myDict = 
          new Dictionary<string, string>();
        // Adding key/value pairs in myDict
        myDict.Add("1", "C");
        myDict.Add("2", "C++");
        myDict.Add("3", "Java");
        myDict.Add("4", "Python");
        myDict.Add("5", "C#");
        myDict.Add("6", "HTML");
        // To get count of key/value pairs in myDict
        Console.WriteLine("Total key/value pairs "+
                "in myDict are : " + myDict.Count);
        myDict.Clear();
        // To get count of key/value pairs in myDict
        Console.WriteLine("Total key/value pairs in "+
             "myDict after Clear() operation are : " + 
                                        myDict.Count);
    }
}
输出:
Total key/value pairs in myDict are : 6
Total key/value pairs in myDict after Clear() operation are : 0

示例 2:

C#


// C# code to remove the entry with
// the specified key from the Dictionary
using System;
using System.Collections.Generic;
class GFG {
    // Driver code
    public static void Main()
    {
        // Create a new dictionary of 
        // strings, with string keys.
        Dictionary<string, string> myDict = 
          new Dictionary<string, string>();
       // Adding key/value pairs in myDict
        myDict.Add("1", "C");
        myDict.Add("2", "C++");
        myDict.Add("3", "Java");
        myDict.Add("4", "Python");
        myDict.Add("5", "C#");
        myDict.Add("6", "HTML");
        // To get count of key/value pairs in myDict
        Console.WriteLine("Total key/value pairs "+
                "in myDict are : " + myDict.Count);
        // Remove the entry with the 
        // specified key from the Dictionary
        myDict.Remove("Russia");
        // To get count of key/value pairs in myDict
        Console.WriteLine("Total key/value pairs in"+
          " myDict after Remove() operation are : " + 
                                       myDict.Count);
    }
}
输出:
Total key/value pairs in myDict are : 6
Total key/value pairs in myDict after Remove() operation are : 6

参考:



相关用法


注:本文由纯净天空筛选整理自rupesh_rao大神的英文原创作品 C# | Dictionary Class。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。