Dictionary<TKey,TValue> Dictionary<TKey,TValue> Dictionary<TKey,TValue> Dictionary<TKey,TValue> Class

定义

表示键和值的集合。Represents a collection of keys and values.

generic <typename TKey, typename TValue>
public ref class Dictionary : System::Collections::Generic::ICollection<System::Collections::Generic::KeyValuePair<TKey, TValue>>, System::Collections::Generic::IDictionary<TKey, TValue>, System::Collections::Generic::IEnumerable<System::Collections::Generic::KeyValuePair<TKey, TValue>>, System::Collections::Generic::IReadOnlyCollection<System::Collections::Generic::KeyValuePair<TKey, TValue>>, System::Collections::Generic::IReadOnlyDictionary<TKey, TValue>, System::Collections::IDictionary, System::Runtime::Serialization::IDeserializationCallback, System::Runtime::Serialization::ISerializable
[System.Runtime.InteropServices.ComVisible(false)]
[System.Serializable]
public class Dictionary<TKey,TValue> : System.Collections.Generic.ICollection<System.Collections.Generic.KeyValuePair<TKey,TValue>>, System.Collections.Generic.IDictionary<TKey,TValue>, System.Collections.Generic.IEnumerable<System.Collections.Generic.KeyValuePair<TKey,TValue>>, System.Collections.Generic.IReadOnlyCollection<System.Collections.Generic.KeyValuePair<TKey,TValue>>, System.Collections.Generic.IReadOnlyDictionary<TKey,TValue>, System.Collections.IDictionary, System.Runtime.Serialization.IDeserializationCallback, System.Runtime.Serialization.ISerializable
type Dictionary<'Key, 'Value> = class
    interface IDictionary<'Key, 'Value>
    interface IDictionary
    interface IReadOnlyDictionary<'Key, 'Value>
    interface ISerializable
    interface IDeserializationCallback
    interface ICollection<KeyValuePair<'Key, 'Value>>
    interface seq<KeyValuePair<'Key, 'Value>>
    interface IEnumerable
    interface ICollection
    interface IReadOnlyCollection<KeyValuePair<'Key, 'Value>>
Public Class Dictionary(Of TKey, TValue)
Implements ICollection(Of KeyValuePair(Of TKey, TValue)), IDeserializationCallback, IDictionary, IDictionary(Of TKey, TValue), IEnumerable(Of KeyValuePair(Of TKey, TValue)), IReadOnlyCollection(Of KeyValuePair(Of TKey, TValue)), IReadOnlyDictionary(Of TKey, TValue), ISerializable

类型参数

TKey

字典中的键的类型。The type of the keys in the dictionary.

TValue

字典中的值的类型。The type of the values in the dictionary.

继承
Dictionary<TKey,TValue>Dictionary<TKey,TValue>Dictionary<TKey,TValue>Dictionary<TKey,TValue>
派生
属性
实现

示例

备注

本文中的 C# 示例运行在 Try.NET 内联代码运行程序和演练环境中。The C# examples in this article run in the Try.NET inline code runner and playground. 选择“运行”按钮以在交互窗口中运行示例 。Select the Run button to run an example in an interactive window. 执行代码后,可通过再次选择“运行”来修改它并运行已修改的代码 。Once you execute the code, you can modify it and run the modified code by selecting Run again. 已修改的代码要么在交互窗口中运行,要么编译失败时,交互窗口将显示所有 C# 编译器错误消息。The modified code either runs in the interactive window or, if compilation fails, the interactive window displays all C# compiler error messages.

下面的代码示例使用字符串键Dictionary<TKey,TValue>创建一个空的字符串, 并Add使用方法来添加一些元素。The following code example creates an empty Dictionary<TKey,TValue> of strings with string keys and uses the Add method to add some elements. 该示例演示AddArgumentException在尝试添加重复键时方法引发。The example demonstrates that the Add method throws an ArgumentException when attempting to add a duplicate key.

该示例使用Item[TKey]属性 (中C#的索引器) 来检索值, 演示在请求KeyNotFoundException的键不存在时引发的, 并显示与键关联的值可以替换。The example uses the Item[TKey] property (the indexer in C#) to retrieve values, demonstrating that a KeyNotFoundException is thrown when a requested key is not present, and showing that the value associated with a key can be replaced.

该示例演示如何使用TryGetValue方法作为更高效的方法来检索值,如果程序必须经常尝试在字典中,不并显示如何使用ContainsKey方法来测试某个键是否存在之前调用Add方法。The example shows how to use the TryGetValue method as a more efficient way to retrieve values if a program often must try key values that are not in the dictionary, and it shows how to use the ContainsKey method to test whether a key exists before calling the Add method.

该示例演示如何枚举字典中的键和值, 以及如何使用Keys属性Values和属性单独枚举键和值。The example shows how to enumerate the keys and values in the dictionary and how to enumerate the keys and values alone using the Keys property and the Values property.

最后, 该示例演示Remove方法。Finally, the example demonstrates the Remove method.

using namespace System;
using namespace System::Collections::Generic;

public ref class Example
{
public:
    static void Main()
    {
        // Create a new dictionary of strings, with string keys.
        //
        Dictionary<String^, String^>^ openWith =
            gcnew Dictionary<String^, String^>();

        // Add some elements to the dictionary. There are no
        // duplicate keys, but some of the values are duplicates.
        openWith->Add("txt", "notepad.exe");
        openWith->Add("bmp", "paint.exe");
        openWith->Add("dib", "paint.exe");
        openWith->Add("rtf", "wordpad.exe");

        // The Add method throws an exception if the new key is
        // already in the dictionary.
        try
        {
            openWith->Add("txt", "winword.exe");
        }
        catch (ArgumentException^)
        {
            Console::WriteLine("An element with Key = \"txt\" already exists.");
        }

        // The Item property is another name for the indexer, so you
        // can omit its name when accessing elements.
        Console::WriteLine("For key = \"rtf\", value = {0}.",
            openWith["rtf"]);

        // The indexer can be used to change the value associated
        // with a key.
        openWith["rtf"] = "winword.exe";
        Console::WriteLine("For key = \"rtf\", value = {0}.",
            openWith["rtf"]);

        // If a key does not exist, setting the indexer for that key
        // adds a new key/value pair.
        openWith["doc"] = "winword.exe";

        // The indexer throws an exception if the requested key is
        // not in the dictionary.
        try
        {
            Console::WriteLine("For key = \"tif\", value = {0}.",
                openWith["tif"]);
        }
        catch (KeyNotFoundException^)
        {
            Console::WriteLine("Key = \"tif\" is not found.");
        }

        // When a program often has to try keys that turn out not to
        // be in the dictionary, TryGetValue can be a more efficient
        // way to retrieve values.
        String^ value = "";
        if (openWith->TryGetValue("tif", value))
        {
            Console::WriteLine("For key = \"tif\", value = {0}.", value);
        }
        else
        {
            Console::WriteLine("Key = \"tif\" is not found.");
        }

        // ContainsKey can be used to test keys before inserting
        // them.
        if (!openWith->ContainsKey("ht"))
        {
            openWith->Add("ht", "hypertrm.exe");
            Console::WriteLine("Value added for key = \"ht\": {0}",
                openWith["ht"]);
        }

        // When you use foreach to enumerate dictionary elements,
        // the elements are retrieved as KeyValuePair objects.
        Console::WriteLine();
        for each( KeyValuePair<String^, String^> kvp in openWith )
        {
            Console::WriteLine("Key = {0}, Value = {1}",
                kvp.Key, kvp.Value);
        }

        // To get the values alone, use the Values property.
        Dictionary<String^, String^>::ValueCollection^ valueColl =
            openWith->Values;

        // The elements of the ValueCollection are strongly typed
        // with the type that was specified for dictionary values.
        Console::WriteLine();
        for each( String^ s in valueColl )
        {
            Console::WriteLine("Value = {0}", s);
        }

        // To get the keys alone, use the Keys property.
        Dictionary<String^, String^>::KeyCollection^ keyColl =
            openWith->Keys;

        // The elements of the KeyCollection are strongly typed
        // with the type that was specified for dictionary keys.
        Console::WriteLine();
        for each( String^ s in keyColl )
        {
            Console::WriteLine("Key = {0}", s);
        }

        // Use the Remove method to remove a key/value pair.
        Console::WriteLine("\nRemove(\"doc\")");
        openWith->Remove("doc");

        if (!openWith->ContainsKey("doc"))
        {
            Console::WriteLine("Key \"doc\" is not found.");
        }
    }
};

int main()
{
    Example::Main();
}

/* This code example produces the following output:

An element with Key = "txt" already exists.
For key = "rtf", value = wordpad.exe.
For key = "rtf", value = winword.exe.
Key = "tif" is not found.
Key = "tif" is not found.
Value added for key = "ht": hypertrm.exe

Key = txt, Value = notepad.exe
Key = bmp, Value = paint.exe
Key = dib, Value = paint.exe
Key = rtf, Value = winword.exe
Key = doc, Value = winword.exe
Key = ht, Value = hypertrm.exe

Value = notepad.exe
Value = paint.exe
Value = paint.exe
Value = winword.exe
Value = winword.exe
Value = hypertrm.exe

Key = txt
Key = bmp
Key = dib
Key = rtf
Key = doc
Key = ht

Remove("doc")
Key "doc" is not found.
 */
// Create a new dictionary of strings, with string keys.
//
Dictionary<string, string> openWith = 
    new Dictionary<string, string>();

// Add some elements to the dictionary. There are no 
// duplicate keys, but some of the values are duplicates.
openWith.Add("txt", "notepad.exe");
openWith.Add("bmp", "paint.exe");
openWith.Add("dib", "paint.exe");
openWith.Add("rtf", "wordpad.exe");

// The Add method throws an exception if the new key is 
// already in the dictionary.
try
{
    openWith.Add("txt", "winword.exe");
}
catch (ArgumentException)
{
    Console.WriteLine("An element with Key = \"txt\" already exists.");
}

// The Item property is another name for the indexer, so you 
// can omit its name when accessing elements. 
Console.WriteLine("For key = \"rtf\", value = {0}.", 
    openWith["rtf"]);

// The indexer can be used to change the value associated
// with a key.
openWith["rtf"] = "winword.exe";
Console.WriteLine("For key = \"rtf\", value = {0}.", 
    openWith["rtf"]);

// If a key does not exist, setting the indexer for that key
// adds a new key/value pair.
openWith["doc"] = "winword.exe";

// The indexer throws an exception if the requested key is
// not in the dictionary.
try
{
    Console.WriteLine("For key = \"tif\", value = {0}.", 
        openWith["tif"]);
}
catch (KeyNotFoundException)
{
    Console.WriteLine("Key = \"tif\" is not found.");
}

// When a program often has to try keys that turn out not to
// be in the dictionary, TryGetValue can be a more efficient 
// way to retrieve values.
string value = "";
if (openWith.TryGetValue("tif", out value))
{
    Console.WriteLine("For key = \"tif\", value = {0}.", value);
}
else
{
    Console.WriteLine("Key = \"tif\" is not found.");
}

// ContainsKey can be used to test keys before inserting 
// them.
if (!openWith.ContainsKey("ht"))
{
    openWith.Add("ht", "hypertrm.exe");
    Console.WriteLine("Value added for key = \"ht\": {0}", 
        openWith["ht"]);
}

// When you use foreach to enumerate dictionary elements,
// the elements are retrieved as KeyValuePair objects.
Console.WriteLine();
foreach( KeyValuePair<string, string> kvp in openWith )
{
    Console.WriteLine("Key = {0}, Value = {1}", 
        kvp.Key, kvp.Value);
}

// To get the values alone, use the Values property.
Dictionary<string, string>.ValueCollection valueColl =
    openWith.Values;

// The elements of the ValueCollection are strongly typed
// with the type that was specified for dictionary values.
Console.WriteLine();
foreach( string s in valueColl )
{
    Console.WriteLine("Value = {0}", s);
}

// To get the keys alone, use the Keys property.
Dictionary<string, string>.KeyCollection keyColl =
    openWith.Keys;

// The elements of the KeyCollection are strongly typed
// with the type that was specified for dictionary keys.
Console.WriteLine();
foreach( string s in keyColl )
{
    Console.WriteLine("Key = {0}", s);
}

// Use the Remove method to remove a key/value pair.
Console.WriteLine("\nRemove(\"doc\")");
openWith.Remove("doc");

if (!openWith.ContainsKey("doc"))
{
    Console.WriteLine("Key \"doc\" is not found.");
}

/* This code example produces the following output:

An element with Key = "txt" already exists.
For key = "rtf", value = wordpad.exe.
For key = "rtf", value = winword.exe.
Key = "tif" is not found.
Key = "tif" is not found.
Value added for key = "ht": hypertrm.exe

Key = txt, Value = notepad.exe
Key = bmp, Value = paint.exe
Key = dib, Value = paint.exe
Key = rtf, Value = winword.exe
Key = doc, Value = winword.exe
Key = ht, Value = hypertrm.exe

Value = notepad.exe
Value = paint.exe
Value = paint.exe
Value = winword.exe
Value = winword.exe
Value = hypertrm.exe

Key = txt
Key = bmp
Key = dib
Key = rtf
Key = doc
Key = ht

Remove("doc")
Key "doc" is not found.
*/
Imports System
Imports System.Collections.Generic

Public Class Example
    
    Public Shared Sub Main() 

        ' Create a new dictionary of strings, with string keys.
        '
        Dim openWith As New Dictionary(Of String, String)
        
        ' Add some elements to the dictionary. There are no 
        ' duplicate keys, but some of the values are duplicates.
        openWith.Add("txt", "notepad.exe")
        openWith.Add("bmp", "paint.exe")
        openWith.Add("dib", "paint.exe")
        openWith.Add("rtf", "wordpad.exe")
        
        ' The Add method throws an exception if the new key is 
        ' already in the dictionary.
        Try
            openWith.Add("txt", "winword.exe")
        Catch 
            Console.WriteLine("An element with Key = ""txt"" already exists.")
        End Try

        ' The Item property is the default property, so you 
        ' can omit its name when accessing elements. 
        Console.WriteLine("For key = ""rtf"", value = {0}.", _
            openWith("rtf"))
        
        ' The default Item property can be used to change the value
        ' associated with a key.
        openWith("rtf") = "winword.exe"
        Console.WriteLine("For key = ""rtf"", value = {0}.", _
            openWith("rtf"))
        
        ' If a key does not exist, setting the default Item property
        ' for that key adds a new key/value pair.
        openWith("doc") = "winword.exe"

        ' The default Item property throws an exception if the requested
        ' key is not in the dictionary.
        Try
            Console.WriteLine("For key = ""tif"", value = {0}.", _
                openWith("tif"))
        Catch 
            Console.WriteLine("Key = ""tif"" is not found.")
        End Try

        ' When a program often has to try keys that turn out not to
        ' be in the dictionary, TryGetValue can be a more efficient 
        ' way to retrieve values.
        Dim value As String = ""
        If openWith.TryGetValue("tif", value) Then
            Console.WriteLine("For key = ""tif"", value = {0}.", value)
        Else
            Console.WriteLine("Key = ""tif"" is not found.")
        End If

        ' ContainsKey can be used to test keys before inserting 
        ' them.
        If Not openWith.ContainsKey("ht") Then
            openWith.Add("ht", "hypertrm.exe")
            Console.WriteLine("Value added for key = ""ht"": {0}", _
                openWith("ht"))
        End If

        ' When you use foreach to enumerate dictionary elements,
        ' the elements are retrieved as KeyValuePair objects.
        Console.WriteLine()
        For Each kvp As KeyValuePair(Of String, String) In openWith
            Console.WriteLine("Key = {0}, Value = {1}", _
                kvp.Key, kvp.Value)
        Next kvp

        ' To get the values alone, use the Values property.
        Dim valueColl As _
            Dictionary(Of String, String).ValueCollection = _
            openWith.Values
        
        ' The elements of the ValueCollection are strongly typed
        ' with the type that was specified for dictionary values.
        Console.WriteLine()
        For Each s As String In  valueColl
            Console.WriteLine("Value = {0}", s)
        Next s

        ' To get the keys alone, use the Keys property.
        Dim keyColl As _
            Dictionary(Of String, String).KeyCollection = _
            openWith.Keys
        
        ' The elements of the KeyCollection are strongly typed
        ' with the type that was specified for dictionary keys.
        Console.WriteLine()
        For Each s As String In  keyColl
            Console.WriteLine("Key = {0}", s)
        Next s

        ' Use the Remove method to remove a key/value pair.
        Console.WriteLine(vbLf + "Remove(""doc"")")
        openWith.Remove("doc")
        
        If Not openWith.ContainsKey("doc") Then
            Console.WriteLine("Key ""doc"" is not found.")
        End If

    End Sub

End Class

' This code example produces the following output:
'
'An element with Key = "txt" already exists.
'For key = "rtf", value = wordpad.exe.
'For key = "rtf", value = winword.exe.
'Key = "tif" is not found.
'Key = "tif" is not found.
'Value added for key = "ht": hypertrm.exe
'
'Key = txt, Value = notepad.exe
'Key = bmp, Value = paint.exe
'Key = dib, Value = paint.exe
'Key = rtf, Value = winword.exe
'Key = doc, Value = winword.exe
'Key = ht, Value = hypertrm.exe
'
'Value = notepad.exe
'Value = paint.exe
'Value = paint.exe
'Value = winword.exe
'Value = winword.exe
'Value = hypertrm.exe
'
'Key = txt
'Key = bmp
'Key = dib
'Key = rtf
'Key = doc
'Key = ht
'
'Remove("doc")
'Key "doc" is not found.
' 

注解

Dictionary<TKey,TValue>泛型类提供一组键到一组值的映射。The Dictionary<TKey,TValue> generic class provides a mapping from a set of keys to a set of values. 每次对字典的添加都包含一个值和与其关联的键。Each addition to the dictionary consists of a value and its associated key. 使用其键检索值的速度非常快, 接近 O (1), 因为该类是作为Dictionary<TKey,TValue>哈希表实现的。Retrieving a value by using its key is very fast, close to O(1), because the Dictionary<TKey,TValue> class is implemented as a hash table.

备注

检索的速度取决于为TKey指定的类型的哈希算法的质量。The speed of retrieval depends on the quality of the hashing algorithm of the type specified for TKey.

只要对象用作中Dictionary<TKey,TValue>的键, 它就不得以任何影响其哈希值的方式进行更改。As long as an object is used as a key in the Dictionary<TKey,TValue>, it must not change in any way that affects its hash value. 根据字典的相等Dictionary<TKey,TValue>比较器, 中的每个键都必须是唯一的。Every key in a Dictionary<TKey,TValue> must be unique according to the dictionary's equality comparer. 键不能为null, 但如果其类型TValue为引用类型, 则值可以为。A key cannot be null, but a value can be, if its type TValue is a reference type.

Dictionary<TKey,TValue>需要一个相等实现来确定键是否相等。Dictionary<TKey,TValue> requires an equality implementation to determine whether keys are equal. 可以通过使用comparer接受参数的构造IEqualityComparer<T>函数来指定泛型接口的实现; 如果不指定实现, 则使用默认的泛型相等比较器EqualityComparer<T>.DefaultYou can specify an implementation of the IEqualityComparer<T> generic interface by using a constructor that accepts a comparer parameter; if you do not specify an implementation, the default generic equality comparer EqualityComparer<T>.Default is used. 如果类型TKey System.IEquatable<T>实现泛型接口, 则默认的相等比较器将使用该实现。If type TKey implements the System.IEquatable<T> generic interface, the default equality comparer uses that implementation.

备注

例如, 你可以使用StringComparer类提供的不区分大小写的字符串比较器来创建具有不区分大小写的字符串键的字典。For example, you can use the case-insensitive string comparers provided by the StringComparer class to create dictionaries with case-insensitive string keys.

的容量Dictionary<TKey,TValue>Dictionary<TKey,TValue>可容纳的元素数。The capacity of a Dictionary<TKey,TValue> is the number of elements the Dictionary<TKey,TValue> can hold. 当向添加元素时Dictionary<TKey,TValue>, 将根据需要通过重新分配内部数组来自动增加容量。As elements are added to a Dictionary<TKey,TValue>, the capacity is automatically increased as required by reallocating the internal array.

仅 .NET Framework: 对于非常大Dictionary<TKey,TValue>的对象, 可以通过在运行时环境中enabled<gcAllowVeryLargeObjects>配置元素的属性设置为true , 来将64位系统上的最大容量增加到2000000000个元素。.NET Framework only: For very large Dictionary<TKey,TValue> objects, you can increase the maximum capacity to 2 billion elements on a 64-bit system by setting the enabled attribute of the <gcAllowVeryLargeObjects> configuration element to true in the run-time environment.

出于枚举目的, 字典中的每一项都被视为KeyValuePair<TKey,TValue>表示值及其键的结构。For purposes of enumeration, each item in the dictionary is treated as a KeyValuePair<TKey,TValue> structure representing a value and its key. 返回项的顺序是不确定的。The order in which the items are returned is undefined.

C#for each语句( C++在VisualBasic中)返回集合中元素的类型的对象。For Each foreachThe foreach statement of the C# language (for each in C++, For Each in Visual Basic) returns an object of the type of the elements in the collection. Dictionary<TKey,TValue>由于是键和值的集合, 因此元素类型不是键的类型或值的类型。Since the Dictionary<TKey,TValue> is a collection of keys and values, the element type is not the type of the key or the type of the value. 相反, 元素类型是KeyValuePair<TKey,TValue>键类型和值类型的。Instead, the element type is a KeyValuePair<TKey,TValue> of the key type and the value type. 例如:For example:

for each(KeyValuePair<String^, String^> kvp in myDictionary)
{
    Console::WriteLine("Key = {0}, Value = {1}", kvp.Key, kvp.Value);
}
foreach( KeyValuePair<string, string> kvp in myDictionary )
{
    Console.WriteLine("Key = {0}, Value = {1}", kvp.Key, kvp.Value);
}
For Each kvp As KeyValuePair(Of String, String) In myDictionary
    Console.WriteLine("Key = {0}, Value = {1}", kvp.Key, kvp.Value)
Next kvp

foreach语句是枚举器周围的包装器, 它只允许从集合读取, 而不允许写入。The foreach statement is a wrapper around the enumerator, which allows only reading from the collection, not writing to it.

备注

因为键可以被继承并且其行为发生了更改, 所以使用Equals方法进行的比较无法保证其绝对唯一性。Because keys can be inherited and their behavior changed, their absolute uniqueness cannot be guaranteed by comparisons using the Equals method.

构造函数

Dictionary<TKey,TValue>() Dictionary<TKey,TValue>() Dictionary<TKey,TValue>() Dictionary<TKey,TValue>()

初始化 Dictionary<TKey,TValue> 类的新实例,该实例为空且具有默认的初始容量,并使用键类型的默认相等比较器。Initializes a new instance of the Dictionary<TKey,TValue> class that is empty, has the default initial capacity, and uses the default equality comparer for the key type.

Dictionary<TKey,TValue>(IDictionary<TKey,TValue>) Dictionary<TKey,TValue>(IDictionary<TKey,TValue>) Dictionary<TKey,TValue>(IDictionary<TKey,TValue>) Dictionary<TKey,TValue>(IDictionary<TKey,TValue>)

初始化 Dictionary<TKey,TValue> 类的新实例,该实例包含从指定的 IDictionary<TKey,TValue> 中复制的元素并为键类型使用默认的相等比较器。Initializes a new instance of the Dictionary<TKey,TValue> class that contains elements copied from the specified IDictionary<TKey,TValue> and uses the default equality comparer for the key type.

Dictionary<TKey,TValue>(IDictionary<TKey,TValue>, IEqualityComparer<TKey>) Dictionary<TKey,TValue>(IDictionary<TKey,TValue>, IEqualityComparer<TKey>) Dictionary<TKey,TValue>(IDictionary<TKey,TValue>, IEqualityComparer<TKey>) Dictionary<TKey,TValue>(IDictionary<TKey,TValue>, IEqualityComparer<TKey>)

初始化 Dictionary<TKey,TValue> 类的新实例,该实例包含从指定的 IDictionary<TKey,TValue> 中复制的元素并使用指定的 IEqualityComparer<T>Initializes a new instance of the Dictionary<TKey,TValue> class that contains elements copied from the specified IDictionary<TKey,TValue> and uses the specified IEqualityComparer<T>.

Dictionary<TKey,TValue>(IEnumerable<KeyValuePair<TKey,TValue>>) Dictionary<TKey,TValue>(IEnumerable<KeyValuePair<TKey,TValue>>) Dictionary<TKey,TValue>(IEnumerable<KeyValuePair<TKey,TValue>>) Dictionary<TKey,TValue>(IEnumerable<KeyValuePair<TKey,TValue>>)
Dictionary<TKey,TValue>(IEnumerable<KeyValuePair<TKey,TValue>>, IEqualityComparer<TKey>) Dictionary<TKey,TValue>(IEnumerable<KeyValuePair<TKey,TValue>>, IEqualityComparer<TKey>) Dictionary<TKey,TValue>(IEnumerable<KeyValuePair<TKey,TValue>>, IEqualityComparer<TKey>) Dictionary<TKey,TValue>(IEnumerable<KeyValuePair<TKey,TValue>>, IEqualityComparer<TKey>)
Dictionary<TKey,TValue>(IEqualityComparer<TKey>) Dictionary<TKey,TValue>(IEqualityComparer<TKey>) Dictionary<TKey,TValue>(IEqualityComparer<TKey>) Dictionary<TKey,TValue>(IEqualityComparer<TKey>)

初始化 Dictionary<TKey,TValue> 类的新实例,该实例为空且具有默认的初始容量,并使用指定的 IEqualityComparer<T>Initializes a new instance of the Dictionary<TKey,TValue> class that is empty, has the default initial capacity, and uses the specified IEqualityComparer<T>.

Dictionary<TKey,TValue>(Int32) Dictionary<TKey,TValue>(Int32) Dictionary<TKey,TValue>(Int32) Dictionary<TKey,TValue>(Int32)

初始化 Dictionary<TKey,TValue> 类的新实例,该实例为空且具有指定的初始容量,并为键类型使用默认的相等比较器。Initializes a new instance of the Dictionary<TKey,TValue> class that is empty, has the specified initial capacity, and uses the default equality comparer for the key type.

Dictionary<TKey,TValue>(Int32, IEqualityComparer<TKey>) Dictionary<TKey,TValue>(Int32, IEqualityComparer<TKey>) Dictionary<TKey,TValue>(Int32, IEqualityComparer<TKey>) Dictionary<TKey,TValue>(Int32, IEqualityComparer<TKey>)

初始化 Dictionary<TKey,TValue> 类的新实例,该实例为空且具有指定的初始容量,并使用指定的 IEqualityComparer<T>Initializes a new instance of the Dictionary<TKey,TValue> class that is empty, has the specified initial capacity, and uses the specified IEqualityComparer<T>.

Dictionary<TKey,TValue>(SerializationInfo, StreamingContext) Dictionary<TKey,TValue>(SerializationInfo, StreamingContext) Dictionary<TKey,TValue>(SerializationInfo, StreamingContext) Dictionary<TKey,TValue>(SerializationInfo, StreamingContext)

用序列化数据初始化 Dictionary<TKey,TValue> 类的新实例。Initializes a new instance of the Dictionary<TKey,TValue> class with serialized data.

属性

Comparer Comparer Comparer Comparer

获取用于确定字典中的键是否相等的 IEqualityComparer<T>Gets the IEqualityComparer<T> that is used to determine equality of keys for the dictionary.

Count Count Count Count

获取包含在 Dictionary<TKey,TValue> 中的键/值对的数目。Gets the number of key/value pairs contained in the Dictionary<TKey,TValue>.

Item[TKey] Item[TKey] Item[TKey] Item[TKey]

获取或设置与指定的键关联的值。Gets or sets the value associated with the specified key.

Keys Keys Keys Keys

获取包含 Dictionary<TKey,TValue> 中的键的集合。Gets a collection containing the keys in the Dictionary<TKey,TValue>.

Values Values Values Values

获取包含 Dictionary<TKey,TValue> 中的值的集合。Gets a collection containing the values in the Dictionary<TKey,TValue>.

方法

Add(TKey, TValue) Add(TKey, TValue) Add(TKey, TValue) Add(TKey, TValue)

将指定的键和值添加到字典中。Adds the specified key and value to the dictionary.

Clear() Clear() Clear() Clear()

将所有键和值从 Dictionary<TKey,TValue> 中移除。Removes all keys and values from the Dictionary<TKey,TValue>.

ContainsKey(TKey) ContainsKey(TKey) ContainsKey(TKey) ContainsKey(TKey)

确定是否 Dictionary<TKey,TValue> 包含指定键。Determines whether the Dictionary<TKey,TValue> contains the specified key.

ContainsValue(TValue) ContainsValue(TValue) ContainsValue(TValue) ContainsValue(TValue)

确定 Dictionary<TKey,TValue> 是否包含特定值。Determines whether the Dictionary<TKey,TValue> contains a specific value.

EnsureCapacity(Int32) EnsureCapacity(Int32) EnsureCapacity(Int32) EnsureCapacity(Int32)

确保字典可容纳指定数量的条目,而无需进一步扩展其后备存储器。Ensures that the dictionary can hold up to a specified number of entries without any further expansion of its backing storage.

Equals(Object) Equals(Object) Equals(Object) Equals(Object)

确定指定的对象是否等于当前对象。Determines whether the specified object is equal to the current object.

(Inherited from Object)
GetEnumerator() GetEnumerator() GetEnumerator() GetEnumerator()

返回循环访问 Dictionary<TKey,TValue> 的枚举数。Returns an enumerator that iterates through the Dictionary<TKey,TValue>.

GetHashCode() GetHashCode() GetHashCode() GetHashCode()

作为默认哈希函数。Serves as the default hash function.

(Inherited from Object)
GetObjectData(SerializationInfo, StreamingContext) GetObjectData(SerializationInfo, StreamingContext) GetObjectData(SerializationInfo, StreamingContext) GetObjectData(SerializationInfo, StreamingContext)

实现 ISerializable 接口,并返回序列化 Dictionary<TKey,TValue> 实例所需的数据。Implements the ISerializable interface and returns the data needed to serialize the Dictionary<TKey,TValue> instance.

GetType() GetType() GetType() GetType()

获取当前实例的 TypeGets the Type of the current instance.

(Inherited from Object)
MemberwiseClone() MemberwiseClone() MemberwiseClone() MemberwiseClone()

创建当前 Object 的浅表副本。Creates a shallow copy of the current Object.

(Inherited from Object)
OnDeserialization(Object) OnDeserialization(Object) OnDeserialization(Object) OnDeserialization(Object)

实现 ISerializable 接口,并在完成反序列化之后引发反序列化事件。Implements the ISerializable interface and raises the deserialization event when the deserialization is complete.

Remove(TKey) Remove(TKey) Remove(TKey) Remove(TKey)

Dictionary<TKey,TValue> 中移除所指定的键的值。Removes the value with the specified key from the Dictionary<TKey,TValue>.

Remove(TKey, TValue) Remove(TKey, TValue) Remove(TKey, TValue) Remove(TKey, TValue)
ToString() ToString() ToString() ToString()

返回表示当前对象的字符串。Returns a string that represents the current object.

(Inherited from Object)
TrimExcess() TrimExcess() TrimExcess() TrimExcess()

如果最初已使用此字典中的所有条目对此字典进行了初始化,则将此字典的容量设置为所需容量。Sets the capacity of this dictionary to what it would be if it had been originally initialized with all its entries.

TrimExcess(Int32) TrimExcess(Int32) TrimExcess(Int32) TrimExcess(Int32)

设置此字典的容量,使其可容纳指定数量的条目,而无需进一步扩展其后备存储器。Sets the capacity of this dictionary to hold up a specified number of entries without any further expansion of its backing storage.

TryAdd(TKey, TValue) TryAdd(TKey, TValue) TryAdd(TKey, TValue) TryAdd(TKey, TValue)

尝试将指定的键和值添加到字典中。Attempts to add the specified key and value to the dictionary.

TryGetValue(TKey, TValue) TryGetValue(TKey, TValue) TryGetValue(TKey, TValue) TryGetValue(TKey, TValue)

获取与指定键关联的值。Gets the value associated with the specified key.

显式界面实现

ICollection.CopyTo(Array, Int32) ICollection.CopyTo(Array, Int32) ICollection.CopyTo(Array, Int32) ICollection.CopyTo(Array, Int32)

从指定的数组索引开始,将 ICollection<T> 中的元素复制到一个数组中。Copies the elements of the ICollection<T> to an array, starting at the specified array index.

ICollection.IsSynchronized ICollection.IsSynchronized ICollection.IsSynchronized ICollection.IsSynchronized

获取一个值,该值指示对 ICollection 的访问是否同步(线程安全)。Gets a value that indicates whether access to the ICollection is synchronized (thread safe).

ICollection.SyncRoot ICollection.SyncRoot ICollection.SyncRoot ICollection.SyncRoot

获取可用于同步对 ICollection 的访问的对象。Gets an object that can be used to synchronize access to the ICollection.

ICollection<KeyValuePair<TKey,TValue>>.Add(KeyValuePair<TKey,TValue>) ICollection<KeyValuePair<TKey,TValue>>.Add(KeyValuePair<TKey,TValue>) ICollection<KeyValuePair<TKey,TValue>>.Add(KeyValuePair<TKey,TValue>) ICollection<KeyValuePair<TKey,TValue>>.Add(KeyValuePair<TKey,TValue>)

添加指定值到带有指定键的 ICollection<T>Adds the specified value to the ICollection<T> with the specified key.

ICollection<KeyValuePair<TKey,TValue>>.Contains(KeyValuePair<TKey,TValue>) ICollection<KeyValuePair<TKey,TValue>>.Contains(KeyValuePair<TKey,TValue>) ICollection<KeyValuePair<TKey,TValue>>.Contains(KeyValuePair<TKey,TValue>) ICollection<KeyValuePair<TKey,TValue>>.Contains(KeyValuePair<TKey,TValue>)

确定是否 ICollection<T> 包含一个指定键和值。Determines whether the ICollection<T> contains a specific key and value.

ICollection<KeyValuePair<TKey,TValue>>.CopyTo(KeyValuePair<TKey,TValue>[], Int32) ICollection<KeyValuePair<TKey,TValue>>.CopyTo(KeyValuePair<TKey,TValue>[], Int32) ICollection<KeyValuePair<TKey,TValue>>.CopyTo(KeyValuePair<TKey,TValue>[], Int32) ICollection<KeyValuePair<TKey,TValue>>.CopyTo(KeyValuePair<TKey,TValue>[], Int32)

从特定的数组索引处开始,将 ICollection<T> 的元素复制到类型 KeyValuePair<TKey,TValue> 的一个数组。Copies the elements of the ICollection<T> to an array of type KeyValuePair<TKey,TValue>, starting at the specified array index.

ICollection<KeyValuePair<TKey,TValue>>.IsReadOnly ICollection<KeyValuePair<TKey,TValue>>.IsReadOnly ICollection<KeyValuePair<TKey,TValue>>.IsReadOnly ICollection<KeyValuePair<TKey,TValue>>.IsReadOnly

获取一个值,该值指示字典是否为只读。Gets a value that indicates whether the dictionary is read-only.

ICollection<KeyValuePair<TKey,TValue>>.Remove(KeyValuePair<TKey,TValue>) ICollection<KeyValuePair<TKey,TValue>>.Remove(KeyValuePair<TKey,TValue>) ICollection<KeyValuePair<TKey,TValue>>.Remove(KeyValuePair<TKey,TValue>) ICollection<KeyValuePair<TKey,TValue>>.Remove(KeyValuePair<TKey,TValue>)

从字典中移除键和值。Removes a key and value from the dictionary.

IDictionary.Add(Object, Object) IDictionary.Add(Object, Object) IDictionary.Add(Object, Object) IDictionary.Add(Object, Object)

将指定的键和值添加到字典中。Adds the specified key and value to the dictionary.

IDictionary.Contains(Object) IDictionary.Contains(Object) IDictionary.Contains(Object) IDictionary.Contains(Object)

确定是否 IDictionary 包含带有指定键的元素。Determines whether the IDictionary contains an element with the specified key.

IDictionary.GetEnumerator() IDictionary.GetEnumerator() IDictionary.GetEnumerator() IDictionary.GetEnumerator()

返回 IDictionaryEnumeratorIDictionaryReturns an IDictionaryEnumerator for the IDictionary.

IDictionary.IsFixedSize IDictionary.IsFixedSize IDictionary.IsFixedSize IDictionary.IsFixedSize

获取一个值,该值指示 IDictionary 是否具有固定大小。Gets a value that indicates whether the IDictionary has a fixed size.

IDictionary.IsReadOnly IDictionary.IsReadOnly IDictionary.IsReadOnly IDictionary.IsReadOnly

获取一个值,该值指示 IDictionary 是否为只读。Gets a value that indicates whether the IDictionary is read-only.

IDictionary.Item[Object] IDictionary.Item[Object] IDictionary.Item[Object] IDictionary.Item[Object]

获取或设置具有指定键的值。Gets or sets the value with the specified key.

IDictionary.Keys IDictionary.Keys IDictionary.Keys IDictionary.Keys

获取包含 ICollection 的键的 IDictionaryGets an ICollection containing the keys of the IDictionary.

IDictionary.Remove(Object) IDictionary.Remove(Object) IDictionary.Remove(Object) IDictionary.Remove(Object)

IDictionary 中移除包含指定键的元素。Removes the element with the specified key from the IDictionary.

IDictionary.Values IDictionary.Values IDictionary.Values IDictionary.Values

获取一个 ICollection,它包含 IDictionary 中的值。Gets an ICollection containing the values in the IDictionary.

IDictionary<TKey,TValue>.Keys IDictionary<TKey,TValue>.Keys IDictionary<TKey,TValue>.Keys IDictionary<TKey,TValue>.Keys

获取包含 ICollection<T> 的键的 IDictionary<TKey,TValue>Gets an ICollection<T> containing the keys of the IDictionary<TKey,TValue>.

IDictionary<TKey,TValue>.Values IDictionary<TKey,TValue>.Values IDictionary<TKey,TValue>.Values IDictionary<TKey,TValue>.Values

获取一个 ICollection<T>,它包含 IDictionary<TKey,TValue> 中的值。Gets an ICollection<T> containing the values in the IDictionary<TKey,TValue>.

IEnumerable.GetEnumerator() IEnumerable.GetEnumerator() IEnumerable.GetEnumerator() IEnumerable.GetEnumerator()

返回一个循环访问集合的枚举器。Returns an enumerator that iterates through the collection.

IEnumerable<KeyValuePair<TKey,TValue>>.GetEnumerator() IEnumerable<KeyValuePair<TKey,TValue>>.GetEnumerator() IEnumerable<KeyValuePair<TKey,TValue>>.GetEnumerator() IEnumerable<KeyValuePair<TKey,TValue>>.GetEnumerator()

返回一个循环访问集合的枚举器。Returns an enumerator that iterates through the collection.

IReadOnlyDictionary<TKey,TValue>.Keys IReadOnlyDictionary<TKey,TValue>.Keys IReadOnlyDictionary<TKey,TValue>.Keys IReadOnlyDictionary<TKey,TValue>.Keys

获取包含 IReadOnlyDictionary<TKey,TValue> 的键的集合。Gets a collection containing the keys of the IReadOnlyDictionary<TKey,TValue>.

IReadOnlyDictionary<TKey,TValue>.Values IReadOnlyDictionary<TKey,TValue>.Values IReadOnlyDictionary<TKey,TValue>.Values IReadOnlyDictionary<TKey,TValue>.Values

获取包含 IReadOnlyDictionary<TKey,TValue> 的值的集合。Gets a collection containing the values of the IReadOnlyDictionary<TKey,TValue>.

扩展方法

GetValueOrDefault<TKey,TValue>(IReadOnlyDictionary<TKey,TValue>, TKey) GetValueOrDefault<TKey,TValue>(IReadOnlyDictionary<TKey,TValue>, TKey) GetValueOrDefault<TKey,TValue>(IReadOnlyDictionary<TKey,TValue>, TKey) GetValueOrDefault<TKey,TValue>(IReadOnlyDictionary<TKey,TValue>, TKey)
GetValueOrDefault<TKey,TValue>(IReadOnlyDictionary<TKey,TValue>, TKey, TValue) GetValueOrDefault<TKey,TValue>(IReadOnlyDictionary<TKey,TValue>, TKey, TValue) GetValueOrDefault<TKey,TValue>(IReadOnlyDictionary<TKey,TValue>, TKey, TValue) GetValueOrDefault<TKey,TValue>(IReadOnlyDictionary<TKey,TValue>, TKey, TValue)
Remove<TKey,TValue>(IDictionary<TKey,TValue>, TKey, TValue) Remove<TKey,TValue>(IDictionary<TKey,TValue>, TKey, TValue) Remove<TKey,TValue>(IDictionary<TKey,TValue>, TKey, TValue) Remove<TKey,TValue>(IDictionary<TKey,TValue>, TKey, TValue)
TryAdd<TKey,TValue>(IDictionary<TKey,TValue>, TKey, TValue) TryAdd<TKey,TValue>(IDictionary<TKey,TValue>, TKey, TValue) TryAdd<TKey,TValue>(IDictionary<TKey,TValue>, TKey, TValue) TryAdd<TKey,TValue>(IDictionary<TKey,TValue>, TKey, TValue)
CopyToDataTable<T>(IEnumerable<T>) CopyToDataTable<T>(IEnumerable<T>) CopyToDataTable<T>(IEnumerable<T>) CopyToDataTable<T>(IEnumerable<T>)

在给定其泛型参数 TDataTable 的输入 DataRow 对象的情况下,返回包含 IEnumerable<T> 对象副本的 DataRowReturns a DataTable that contains copies of the DataRow objects, given an input IEnumerable<T> object where the generic parameter T is DataRow.

CopyToDataTable<T>(IEnumerable<T>, DataTable, LoadOption) CopyToDataTable<T>(IEnumerable<T>, DataTable, LoadOption) CopyToDataTable<T>(IEnumerable<T>, DataTable, LoadOption) CopyToDataTable<T>(IEnumerable<T>, DataTable, LoadOption)

在给定其泛型参数 TDataRow 的输入 DataTable 对象的情况下,将 IEnumerable<T> 对象复制到指定的 DataRowCopies DataRow objects to the specified DataTable, given an input IEnumerable<T> object where the generic parameter T is DataRow.

CopyToDataTable<T>(IEnumerable<T>, DataTable, LoadOption, FillErrorEventHandler) CopyToDataTable<T>(IEnumerable<T>, DataTable, LoadOption, FillErrorEventHandler) CopyToDataTable<T>(IEnumerable<T>, DataTable, LoadOption, FillErrorEventHandler) CopyToDataTable<T>(IEnumerable<T>, DataTable, LoadOption, FillErrorEventHandler)

在给定其泛型参数 TDataRow 的输入 DataTable 对象的情况下,将 IEnumerable<T> 对象复制到指定的 DataRowCopies DataRow objects to the specified DataTable, given an input IEnumerable<T> object where the generic parameter T is DataRow.

Cast<TResult>(IEnumerable) Cast<TResult>(IEnumerable) Cast<TResult>(IEnumerable) Cast<TResult>(IEnumerable)

IEnumerable 的元素强制转换为指定的类型。Casts the elements of an IEnumerable to the specified type.

OfType<TResult>(IEnumerable) OfType<TResult>(IEnumerable) OfType<TResult>(IEnumerable) OfType<TResult>(IEnumerable)

根据指定类型筛选 IEnumerable 的元素。Filters the elements of an IEnumerable based on a specified type.

AsParallel(IEnumerable) AsParallel(IEnumerable) AsParallel(IEnumerable) AsParallel(IEnumerable)

启用查询的并行化。Enables parallelization of a query.

AsQueryable(IEnumerable) AsQueryable(IEnumerable) AsQueryable(IEnumerable) AsQueryable(IEnumerable)

IEnumerable 转换为 IQueryableConverts an IEnumerable to an IQueryable.

Ancestors<T>(IEnumerable<T>) Ancestors<T>(IEnumerable<T>) Ancestors<T>(IEnumerable<T>) Ancestors<T>(IEnumerable<T>)

返回元素集合,其中包含源集合中每个节点的上级。Returns a collection of elements that contains the ancestors of every node in the source collection.

Ancestors<T>(IEnumerable<T>, XName) Ancestors<T>(IEnumerable<T>, XName) Ancestors<T>(IEnumerable<T>, XName) Ancestors<T>(IEnumerable<T>, XName)

返回经过筛选的元素集合,其中包含源集合中每个节点的上级。Returns a filtered collection of elements that contains the ancestors of every node in the source collection. 集合中仅包括具有匹配 XName 的元素。Only elements that have a matching XName are included in the collection.

DescendantNodes<T>(IEnumerable<T>) DescendantNodes<T>(IEnumerable<T>) DescendantNodes<T>(IEnumerable<T>) DescendantNodes<T>(IEnumerable<T>)

返回源集合中每个文档和元素的子代节点的集合。Returns a collection of the descendant nodes of every document and element in the source collection.

Descendants<T>(IEnumerable<T>) Descendants<T>(IEnumerable<T>) Descendants<T>(IEnumerable<T>) Descendants<T>(IEnumerable<T>)

返回元素集合,其中包含源集合中每个元素和文档的子代元素。Returns a collection of elements that contains the descendant elements of every element and document in the source collection.

Descendants<T>(IEnumerable<T>, XName) Descendants<T>(IEnumerable<T>, XName) Descendants<T>(IEnumerable<T>, XName) Descendants<T>(IEnumerable<T>, XName)

返回经过筛选的元素集合,其中包含源集合中每个元素和文档的子代元素。Returns a filtered collection of elements that contains the descendant elements of every element and document in the source collection. 集合中仅包括具有匹配 XName 的元素。Only elements that have a matching XName are included in the collection.

Elements<T>(IEnumerable<T>) Elements<T>(IEnumerable<T>) Elements<T>(IEnumerable<T>) Elements<T>(IEnumerable<T>)

返回源集合中每个元素和文档的子元素的集合。Returns a collection of the child elements of every element and document in the source collection.

Elements<T>(IEnumerable<T>, XName) Elements<T>(IEnumerable<T>, XName) Elements<T>(IEnumerable<T>, XName) Elements<T>(IEnumerable<T>, XName)

返回源集合中经过筛选的每个元素和文档的子元素集合。Returns a filtered collection of the child elements of every element and document in the source collection. 集合中仅包括具有匹配 XName 的元素。Only elements that have a matching XName are included in the collection.

InDocumentOrder<T>(IEnumerable<T>) InDocumentOrder<T>(IEnumerable<T>) InDocumentOrder<T>(IEnumerable<T>) InDocumentOrder<T>(IEnumerable<T>)

返回节点集合(其中包含源集合中的所有节点),并按文档顺序排列。Returns a collection of nodes that contains all nodes in the source collection, sorted in document order.

Nodes<T>(IEnumerable<T>) Nodes<T>(IEnumerable<T>) Nodes<T>(IEnumerable<T>) Nodes<T>(IEnumerable<T>)

返回源集合中每个文档和元素的子节点集合。Returns a collection of the child nodes of every document and element in the source collection.

Remove<T>(IEnumerable<T>) Remove<T>(IEnumerable<T>) Remove<T>(IEnumerable<T>) Remove<T>(IEnumerable<T>)

将源集合中的每个节点从其父节点中移除。Removes every node in the source collection from its parent node.

适用于

线程安全性

只要不修改集合,就可以同时支持多个读取器。Dictionary<TKey,TValue>A Dictionary<TKey,TValue> can support multiple readers concurrently, as long as the collection is not modified. 尽管如此, 枚举集合本身并不是一个线程安全的过程。Even so, enumerating through a collection is intrinsically not a thread-safe procedure. 在具有写入访问的枚举竞争的罕见情况下, 必须在整个枚举过程中锁定集合。In the rare case where an enumeration contends with write accesses, the collection must be locked during the entire enumeration. 若要允许多个线程访问集合以进行读写操作,则必须实现自己的同步。To allow the collection to be accessed by multiple threads for reading and writing, you must implement your own synchronization.

有关线程安全的替代,请参阅 ConcurrentDictionary<TKey,TValue> 类或 ImmutableDictionary<TKey,TValue> 类。For thread-safe alternatives, see the ConcurrentDictionary<TKey,TValue> class or ImmutableDictionary<TKey,TValue> class.

此类型的Shared公共静态 (在 Visual Basic) 成员是线程安全的。Public static (Shared in Visual Basic) members of this type are thread safe.

另请参阅