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)而不是 o(n)(对于 SortedList<TKey,TValue>)。
如果列表从已排序的数据中一次性填充所有,则 SortedList<TKey,TValue> 的速度比 SortedDictionary<TKey,TValue>快。
每个键/值对都可以作为 KeyValuePair<TKey,TValue> 结构检索,也可以作为 DictionaryEntry 通过非泛型 IDictionary 接口进行检索。
键必须不可变,只要它们用作 SortedDictionary<TKey,TValue>中的键。
SortedDictionary<TKey,TValue> 中的每个密钥都必须是唯一的。 如果值类型 TValue
为引用类型,则键不能 null
,但值可以是。
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> 就可以同时支持多个读取器。 即便如此,通过集合进行枚举本质上不是线程安全的过程。 若要保证枚举期间的线程安全性,可以在整个枚举期间锁定集合。 若要允许多个线程访问集合进行读取和写入,必须实现自己的同步。