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 (記錄 n) ,而不是針對 SortedList<TKey,TValue>的 O (n) 。
如果清單一次從已排序的數據填入全部, SortedList<TKey,TValue> 則比 快 SortedDictionary<TKey,TValue>。
每個索引鍵/值組都可以擷取為KeyValuePair<TKey,TValue>結構,或透過非一般IDictionary介面擷取為 DictionaryEntry 。
只要索引鍵做為 中的 SortedDictionary<TKey,TValue>索引鍵使用,就必須不可變。 中的每個索引鍵都必須是唯一 SortedDictionary<TKey,TValue> 的。 如果實值型別是參考型TValue
別,索引鍵不能是 null
,但值可以是 。
SortedDictionary<TKey,TValue> 需要比較子實作才能執行索引鍵比較。 您可以使用接受comparer
參數的建構函式來指定泛型介面的IComparer<T>實作;如果您未指定實作,則會使用預設的泛型比較子Comparer<T>.Default。 如果類型 TKey
實作 System.IComparable<T> 泛型介面,則預設比較子會使用該實作。
foreach
C++ 中 C# 語言 (for each
的 語句,For Each
在 Visual Basic 中) 會傳回集合中專案類型的 物件。 因為的每個 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 |
取得用來排序 IComparer<T> 之項目的 SortedDictionary<TKey,TValue>。 |
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) |
取得與指定索引鍵關聯的值。 |
明確介面實作
擴充方法
適用於
執行緒安全性
Visual Basic 中的公用靜態 (Shared
) 此類型的成員是安全線程。 並非所有的執行個體成員都是安全執行緒。
SortedDictionary<TKey,TValue>可以同時支援多個讀取器,只要集合未修改即可。 即使如此,透過集合列舉本質上不是安全線程的程式。 若要確保列舉期間的執行緒安全性,您可以在整個列舉期間鎖定集合。 若要讓多重執行緒能夠存取集合以便進行讀取和寫入,您必須實作自己的同步處理。
另請參閱
意見反應
https://aka.ms/ContentUserFeedback。
即將登場:在 2024 年,我們將逐步淘汰 GitHub 問題作為內容的意見反應機制,並將它取代為新的意見反應系統。 如需詳細資訊,請參閱:提交並檢視相關的意見反應