📜  C#|字典类

📅  最后修改于: 2021-05-29 17:55:20             🧑  作者: Mango

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

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

参数:

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

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

建设者

Constructor Description
Dictionary() Initializes a new instance of the Dictionary class that is empty, has the default initial capacity, and uses the default equality comparer for the key type.
Dictionary(IDictionary) Initializes a new instance of the Dictionary class that contains elements copied from the specified IDictionary and uses the default equality comparer for the key type.
Dictionary(IDictionary, IEqualityComparer) Initializes a new instance of the Dictionary class that contains elements copied from the specified IDictionary and uses the specified IEqualityComparer.
Dictionary(IEqualityComparer) Initializes a new instance of the Dictionary class that is empty, has the default initial capacity, and uses the specified IEqualityComparer.
Dictionary(Int32) Initializes a new instance of the Dictionary class that is empty, has the specified initial capacity and uses the default equality comparer for the key type.
Dictionary(Int32, IEqualityComparer) Initializes a new instance of the Dictionary class that is empty, has the specified initial capacity, and uses the specified IEqualityComparer.
Dictionary(SerializationInfo, StreamingContext) Initializes a new instance of the Dictionary class with serialized data.

例子:

// 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 myDict = 
          new Dictionary();
  
        // 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 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 Description
Comparer Gets the IEqualityComparer that is used to determine equality of keys for the dictionary.
Count Gets the number of key/value pairs contained in the Dictionary.
Item[TKey] Gets or sets the value associated with the specified key.
Keys Gets a collection containing the keys in the Dictionary.
Values Gets a collection containing the values in the Dictionary.

范例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 myDict = 
          new Dictionary();
  
        // 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.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 myDict = 
           new Dictionary();
  
        // 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.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

方法

Method Description
Add(TKey, TValue) Adds the specified key and value to the dictionary.
Clear() Removes all keys and values from the Dictionary.
ContainsKey(TKey) Determines whether the Dictionary contains the specified key.
ContainsValue(TValue) Determines whether the Dictionary contains a specific value.
Equals(Object) Determines whether the specified object is equal to the current object.
GetEnumerator() Returns an enumerator that iterates through the Dictionary .
GetHashCode() Serves as the default hash function.
GetObjectData(SerializationInfo, StreamingContext) Implements the ISerializable interface and returns the data needed to serialize the Dictionary instance.
GetType() Gets the Type of the current instance.
MemberwiseClone() Creates a shallow copy of the current Object.
OnDeserialization(Object) Implements the ISerializable interface and raises the deserialization event when the deserialization is complete.
Remove(TKey) Removes the value with the specified key from the Dictionary.
ToString() Returns a string that represents the current object.
TryGetValue(TKey, TValue) Gets the value associated with the specified key.

范例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 myDict = 
          new Dictionary();
  
        // 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 myDict = 
          new Dictionary();
  
       // 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/zh-cn/dotnet/api/system.collections.generic.dictionary-2?view=netframework-4.7.2