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. 這個範例會示範Add ArgumentException當嘗試加入重複的索引鍵時,方法會擲回。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.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>.Default子。You 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>的物件,您可以在執行時間環境中,將<gcAllowVeryLargeObjects> configuration 專案的enabled屬性設為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.

foreach for each語言的語句(在 Visual Basic 中C++ )會傳回集合中元素類型的物件。For Each C#The 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 的淺層複本 (Shallow Copy)。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,包含 IDictionary 的索引鍵。Gets 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>)

根據輸入 DataTable 物件 (其中泛型參數 TDataRow) 傳回包含 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)

根據輸入 DataRow 物件 (其中泛型參數 TDataTable),將 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)

根據輸入 DataRow 物件 (其中泛型參數 TDataTable),將 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.

另請參閱