SortedDictionary<TKey,TValue> 類別
定義
重要
部分資訊涉及發行前產品,在發行之前可能會有大幅修改。 Microsoft 對此處提供的資訊,不做任何明確或隱含的瑕疵擔保。
表示索引鍵/值組的集合,這些索引鍵/值組是在索引鍵上排序。
generic <typename TKey, typename TValue>
public ref class SortedDictionary : 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
generic <typename TKey, typename TValue>
public ref class SortedDictionary : 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::IDictionary
public class SortedDictionary<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.Serializable]
public class SortedDictionary<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.IDictionary
[System.Serializable]
public class SortedDictionary<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
public class SortedDictionary<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.IDictionary
type SortedDictionary<'Key, 'Value> = class
interface ICollection<KeyValuePair<'Key, 'Value>>
interface seq<KeyValuePair<'Key, 'Value>>
interface IEnumerable
interface IDictionary<'Key, 'Value>
interface IReadOnlyCollection<KeyValuePair<'Key, 'Value>>
interface IReadOnlyDictionary<'Key, 'Value>
interface ICollection
interface IDictionary
[<System.Serializable>]
type SortedDictionary<'Key, 'Value> = class
interface IDictionary<'Key, 'Value>
interface ICollection<KeyValuePair<'Key, 'Value>>
interface seq<KeyValuePair<'Key, 'Value>>
interface IDictionary
interface ICollection
interface IEnumerable
[<System.Serializable>]
type SortedDictionary<'Key, 'Value> = class
interface IDictionary<'Key, 'Value>
interface ICollection<KeyValuePair<'Key, 'Value>>
interface seq<KeyValuePair<'Key, 'Value>>
interface IEnumerable
interface IDictionary
interface ICollection
interface IReadOnlyDictionary<'Key, 'Value>
interface IReadOnlyCollection<KeyValuePair<'Key, 'Value>>
type SortedDictionary<'Key, 'Value> = class
interface IDictionary<'Key, 'Value>
interface ICollection<KeyValuePair<'Key, 'Value>>
interface seq<KeyValuePair<'Key, 'Value>>
interface IDictionary
interface ICollection
interface IEnumerable
Public Class SortedDictionary(Of TKey, TValue)
Implements ICollection(Of KeyValuePair(Of TKey, TValue)), IDictionary, IDictionary(Of TKey, TValue), IEnumerable(Of KeyValuePair(Of TKey, TValue)), IReadOnlyCollection(Of KeyValuePair(Of TKey, TValue)), IReadOnlyDictionary(Of TKey, TValue)
Public Class SortedDictionary(Of TKey, TValue)
Implements ICollection(Of KeyValuePair(Of TKey, TValue)), IDictionary, IDictionary(Of TKey, TValue), IEnumerable(Of KeyValuePair(Of TKey, TValue))
類型參數
- TKey
字典中索引鍵的類型。
- TValue
字典中值的型別。
- 繼承
-
SortedDictionary<TKey,TValue>
- 屬性
- 實作
-
ICollection<KeyValuePair<TKey,TValue>> IDictionary<TKey,TValue> IEnumerable<KeyValuePair<TKey,TValue>> IEnumerable<T> IReadOnlyCollection<KeyValuePair<TKey,TValue>> IReadOnlyDictionary<TKey,TValue> ICollection IDictionary IEnumerable
範例
下列程式代碼範例會使用字串索引鍵建立空的字串 SortedDictionary<TKey,TValue>,並使用 Add 方法來新增某些元素。 此範例示範嘗試新增重複索引鍵時,Add 方法會擲回 ArgumentException。
此範例會使用 Item[] 屬性 (C# 中的索引器) 來擷取值,示範當要求索引鍵不存在時擲回 KeyNotFoundException,並顯示可以取代與索引鍵相關聯的值。
此範例示範如何使用 TryGetValue 方法,以更有效率的方式擷取值,如果程式經常必須嘗試不在字典中的索引鍵值,並示範如何使用 ContainsKey 方法來測試索引鍵是否存在,然後再呼叫 Add 方法。
此範例示範如何列舉字典中的索引鍵和值,以及如何單獨使用 Keys 屬性和 Values 屬性列舉索引鍵和值。
最後,此範例示範 Remove 方法。
using System;
using System.Collections.Generic;
public class Example
{
public static void Main()
{
// Create a new sorted dictionary of strings, with string
// keys.
SortedDictionary<string, string> openWith =
new SortedDictionary<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.
SortedDictionary<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.
SortedDictionary<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 = bmp, Value = paint.exe
Key = dib, Value = paint.exe
Key = doc, Value = winword.exe
Key = ht, Value = hypertrm.exe
Key = rtf, Value = winword.exe
Key = txt, Value = notepad.exe
Value = paint.exe
Value = paint.exe
Value = winword.exe
Value = hypertrm.exe
Value = winword.exe
Value = notepad.exe
Key = bmp
Key = dib
Key = doc
Key = ht
Key = rtf
Key = txt
Remove("doc")
Key "doc" is not found.
*/
Imports System.Collections.Generic
Public Class Example
Public Shared Sub Main()
' Create a new sorted dictionary of strings, with string
' keys.
Dim openWith As New SortedDictionary(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 SortedDictionary(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 SortedDictionary(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 = bmp, Value = paint.exe
'Key = dib, Value = paint.exe
'Key = doc, Value = winword.exe
'Key = ht, Value = hypertrm.exe
'Key = rtf, Value = winword.exe
'Key = txt, Value = notepad.exe
'
'Value = paint.exe
'Value = paint.exe
'Value = winword.exe
'Value = hypertrm.exe
'Value = winword.exe
'Value = notepad.exe
'
'Key = bmp
'Key = dib
'Key = doc
'Key = ht
'Key = rtf
'Key = txt
'
'Remove("doc")
'Key "doc" is not found.
'
備註
SortedDictionary<TKey,TValue> 泛型類別是具有 O(log n) 擷取的二進位搜尋樹狀結構,其中 n 是字典中的元素數目。 在這方面,它類似於 SortedList<TKey,TValue> 泛型類別。 這兩個類別具有類似的物件模型,而且兩者都有 O(log n) 擷取。 兩個類別的差異在於記憶體使用和插入和移除的速度:
SortedList<TKey,TValue> 使用的記憶體小於 SortedDictionary<TKey,TValue>。
SortedDictionary<TKey,TValue> 針對未排序的數據具有更快的插入和移除作業:O(log n) 與 SortedList<TKey,TValue>的 O(n) 相反。
如果已從已排序的數據一次填入清單,SortedList<TKey,TValue> 的速度會比 SortedDictionary<TKey,TValue>快。
每個索引鍵/值組都可以擷取為 KeyValuePair<TKey,TValue> 結構,或透過非泛型 IDictionary 介面來擷取為 DictionaryEntry。
只要索引鍵作為 SortedDictionary<TKey,TValue>中的索引鍵,就必須是固定的。
SortedDictionary<TKey,TValue> 中的每個索引鍵都必須是唯一的。 索引鍵不能 null
,但如果實值型別 TValue
為參考型別,則可以是值。
SortedDictionary<TKey,TValue> 需要比較子實作來執行索引鍵比較。 您可以使用接受 comparer
參數的建構函式來指定 IComparer<T> 泛型介面的實作;如果您未指定實作,則會使用預設的泛型比較子 Comparer<T>.Default。 如果類型 TKey
實作 System.IComparable<T> 泛型介面,則預設比較子會使用該實作。
C# 語言的 foreach
語句 (for each
在 C++ 中,在 Visual Basic 中 For Each
) 會傳回集合中專案類型的 物件。 由於 SortedDictionary<TKey,TValue> 的每個元素都是索引鍵/值組,因此項目類型不是索引鍵的類型或值的型別。 相反地,元素類型會 KeyValuePair<TKey,TValue>。 下列程式代碼顯示 C#、C++ 和 Visual Basic 語法。
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
語句是列舉值周圍的包裝函式,它只允許從集合讀取,而不是寫入集合。
建構函式
SortedDictionary<TKey,TValue>() |
初始化空的 SortedDictionary<TKey,TValue> 類別的新實例,並使用索引鍵類型的預設 IComparer<T> 實作。 |
SortedDictionary<TKey,TValue>(IComparer<TKey>) |
初始化空的 SortedDictionary<TKey,TValue> 類別的新實例,並使用指定的 IComparer<T> 實作來比較索引鍵。 |
SortedDictionary<TKey,TValue>(IDictionary<TKey,TValue>) |
初始化 SortedDictionary<TKey,TValue> 類別的新實例,其中包含從指定的 IDictionary<TKey,TValue> 複製的專案,並使用索引鍵類型的預設 IComparer<T> 實作。 |
SortedDictionary<TKey,TValue>(IDictionary<TKey,TValue>, IComparer<TKey>) |
初始化 SortedDictionary<TKey,TValue> 類別的新實例,其中包含從指定的 IDictionary<TKey,TValue> 複製的專案,並使用指定的 IComparer<T> 實作來比較索引鍵。 |
屬性
Comparer |
取得用來排序 SortedDictionary<TKey,TValue>專案的 IComparer<T>。 |
Count |
取得包含在 SortedDictionary<TKey,TValue>中的索引鍵/值組數目。 |
Item[TKey] |
取得或設定與指定索引鍵相關聯的值。 |
Keys |
取得集合,其中包含 SortedDictionary<TKey,TValue>中的索引鍵。 |
Values |
取得集合,其中包含 SortedDictionary<TKey,TValue>中的值。 |
方法
Add(TKey, TValue) |
將具有指定索引鍵和值的專案加入至 SortedDictionary<TKey,TValue>。 |
Clear() |
從 SortedDictionary<TKey,TValue>移除所有專案。 |
ContainsKey(TKey) |
判斷 SortedDictionary<TKey,TValue> 是否包含具有指定索引鍵的專案。 |
ContainsValue(TValue) |
判斷 SortedDictionary<TKey,TValue> 是否包含具有指定值的專案。 |
CopyTo(KeyValuePair<TKey,TValue>[], Int32) |
從指定的索引開始,將 SortedDictionary<TKey,TValue> 的項目複製到指定的 KeyValuePair<TKey,TValue> 結構陣列。 |
Equals(Object) |
判斷指定的物件是否等於目前的物件。 (繼承來源 Object) |
GetEnumerator() |
傳回逐一查看 SortedDictionary<TKey,TValue>的列舉值。 |
GetHashCode() |
做為預設哈希函式。 (繼承來源 Object) |
GetType() |
取得目前實例的 Type。 (繼承來源 Object) |
MemberwiseClone() |
建立目前 Object的淺層複本。 (繼承來源 Object) |
Remove(TKey) |
從 SortedDictionary<TKey,TValue>移除具有指定索引鍵的專案。 |
ToString() |
傳回表示目前 物件的字串。 (繼承來源 Object) |
TryGetValue(TKey, TValue) |
取得與指定索引鍵相關聯的值。 |
明確介面實作
擴充方法
適用於
執行緒安全性
此類型的公用靜態 (Shared
) 成員是安全線程。 不保證任何實例成員都是安全線程。
只要集合未修改,SortedDictionary<TKey,TValue> 就可以同時支援多個讀取器。 即便如此,透過集合列舉本質上不是安全線程的程式。 若要保證列舉期間的線程安全性,您可以在整個列舉期間鎖定集合。 若要允許多個線程存取集合以進行讀取和寫入,您必須實作自己的同步處理。