C#字典Dictionary类用法介绍

2021年5月9日16:39:51 发表评论 1,315 次浏览

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

注意:键不能为null, 但值可以是(如果值类型为价值是引用类型。

参数:

  • TKey:表示字典中键的类型。
  • TValue:表示字典中值的类型。

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

构造器

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

例子:

//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

属性

属性 描述
Comparer 获取IEqualityComparer <TKey, TValue>, 该IEqualityComparer <TKey, TValue>用于确定字典的键是否相等。
Count 获取包含在Dictionary <TKey, TValue>中的键/值对的数量。
Item[TKey] 获取或设置与指定键关联的值。
Keys 获取一个包含Dictionary <TKey, TValue>中的键的集合。
Values 获取一个包含Dictionary <TKey, TValue>中的值的集合。

示例1:

//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# 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

方法

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

示例1:

//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# 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

参考:

  • https://docs.microsoft.com/en-us/dotnet/api/system.collections.generic.dictionary-2?view=netframework-4.7.2

木子山

发表评论

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: