SortedList<TKey,TValue> SortedList<TKey,TValue> SortedList<TKey,TValue> SortedList<TKey,TValue> Class

定义

表示基于相关的 IComparer<T> 实现按键进行排序的键/值对的集合。Represents a collection of key/value pairs that are sorted by key based on the associated IComparer<T> implementation.

generic <typename TKey, typename TValue>
public ref class SortedList : 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.InteropServices.ComVisible(false)]
[System.Serializable]
public class SortedList<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
type SortedList<'Key, 'Value> = class
    interface IDictionary<'Key, 'Value>
    interface IDictionary
    interface IReadOnlyDictionary<'Key, 'Value>
    interface ICollection<KeyValuePair<'Key, 'Value>>
    interface seq<KeyValuePair<'Key, 'Value>>
    interface IEnumerable
    interface ICollection
    interface IReadOnlyCollection<KeyValuePair<'Key, 'Value>>
Public Class SortedList(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)

类型参数

TKey

集合中的键的类型。The type of keys in the collection.

TValue

集合中值的类型。The type of values in the collection.

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

示例

下面的代码示例使用字符串键SortedList<TKey,TValue>创建一个空的字符串, 并Add使用方法来添加一些元素。The following code example creates an empty SortedList<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 sorted list, 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 sorted list 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 <System.dll>

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

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

        // Add some elements to the list. 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 list.
        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 list.
        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 list, 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 list 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.
        IList<String^>^ ilistValues = openWith->Values;

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

        // The Values property is an efficient way to retrieve
        // values by index.
        Console::WriteLine("\nIndexed retrieval using the Values " +
            "property: Values[2] = {0}", openWith->Values[2]);

        // To get the keys alone, use the Keys property.
        IList<String^>^ ilistKeys = openWith->Keys;

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

        // The Keys property is an efficient way to retrieve
        // keys by index.
        Console::WriteLine("\nIndexed retrieval using the Keys " +
            "property: Keys[2] = {0}", openWith->Keys[2]);

        // 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 = 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

Indexed retrieval using the Values property: Values[2] = winword.exe

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

Indexed retrieval using the Keys property: Keys[2] = doc

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

public class Example
{
    public static void Main()
    {
        // Create a new sorted list of strings, with string
        // keys.
        SortedList<string, string> openWith = 
            new SortedList<string, string>();

        // Add some elements to the list. 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 list.
        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 list.
        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 list, 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 list 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.
        IList<string> ilistValues = openWith.Values;

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

        // The Values property is an efficient way to retrieve
        // values by index.
        Console.WriteLine("\nIndexed retrieval using the Values " +
            "property: Values[2] = {0}", openWith.Values[2]);

        // To get the keys alone, use the Keys property.
        IList<string> ilistKeys = openWith.Keys;

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

        // The Keys property is an efficient way to retrieve
        // keys by index.
        Console.WriteLine("\nIndexed retrieval using the Keys " +
            "property: Keys[2] = {0}", openWith.Keys[2]);

        // 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

Indexed retrieval using the Values property: Values[2] = winword.exe

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

Indexed retrieval using the Keys property: Keys[2] = doc

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

Public Class Example
    
    Public Shared Sub Main() 

        ' Create a new sorted list of strings, with string 
        ' keys. 
        Dim openWith As New SortedList(Of String, String)
        
        ' Add some elements to the list. 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 list.
        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 list.
        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 list, 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 list 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 ilistValues As IList(Of String) = openWith.Values
        
        ' The elements of the list are strongly typed with the
        ' type that was specified for the SortedList values.
        Console.WriteLine()
        For Each s As String In ilistValues
            Console.WriteLine("Value = {0}", s)
        Next s

        ' The Values property is an efficient way to retrieve
        ' values by index.
        Console.WriteLine(vbLf & "Indexed retrieval using the " & _
            "Values property: Values(2) = {0}", openWith.Values(2))

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

        ' The Keys property is an efficient way to retrieve
        ' keys by index.
        Console.WriteLine(vbLf & "Indexed retrieval using the " & _
            "Keys property: Keys(2) = {0}", openWith.Keys(2))

        ' 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
'
'Indexed retrieval using the Values property: Values(2) = winword.exe
'
'Key = bmp
'Key = dib
'Key = doc
'Key = ht
'Key = rtf
'Key = txt
'
'Indexed retrieval using the Keys property: Keys(2) = doc
'
'Remove("doc")
'Key "doc" is not found.
' 

注解

泛型类是带有 O (日志n) 检索的键/值对的数组, 其中 n 是字典中的元素数。 SortedList<TKey,TValue>The SortedList<TKey,TValue> generic class is an array of key/value pairs with O(log n) retrieval, where n is the number of elements in the dictionary. 在这种情况下, 它类似SortedDictionary<TKey,TValue>于泛型类。In this, it is similar to the SortedDictionary<TKey,TValue> generic class. 这两个类具有相似的对象模型, 并且都具有 O n(log) 检索。The two classes have similar object models, and both have O(log n) retrieval. 这两个类的不同之处在于内存使用和插入和删除的速度:Where the two classes differ is in memory use and speed of insertion and removal:

SortedDictionary<TKey,TValue> SortedList<TKey,TValue>Values Keys类之间的另一个区别是, 支持通过和属性所返回的集合高效检索键和值的索引。 SortedList<TKey,TValue>Another difference between the SortedDictionary<TKey,TValue> and SortedList<TKey,TValue> classes is that SortedList<TKey,TValue> supports efficient indexed retrieval of keys and values through the collections returned by the Keys and Values properties. 访问属性时无需重新生成列表, 因为这些列表只是键和值的内部数组的包装器。It is not necessary to regenerate the lists when the properties are accessed, because the lists are just wrappers for the internal arrays of keys and values. 下面的代码演示如何使用Values属性从字符串的排序列表中检索值的索引:The following code shows the use of the Values property for indexed retrieval of values from a sorted list of strings:

String^ v = mySortedList->Values[3];
string v = mySortedList.Values[3];
Dim v As String = mySortedList.Values(3)

SortedList<TKey,TValue>作为键/值对的数组实现, 按键进行排序。SortedList<TKey,TValue> is implemented as an array of key/value pairs, sorted by the key. 每个元素都可以作为一个KeyValuePair<TKey,TValue>对象进行检索。Each element can be retrieved as a KeyValuePair<TKey,TValue> object.

关键对象在中用作键时, 它们必须是不可变的SortedList<TKey,TValue>Key objects must be immutable as long as they are used as keys in the SortedList<TKey,TValue>. 中的每个SortedList<TKey,TValue>键都必须是唯一的。Every key in a SortedList<TKey,TValue> must be unique. 键不能为null, 但如果TValue列表中值的类型为引用类型, 则值可以为。A key cannot be null, but a value can be, if the type of values in the list, TValue, is a reference type.

SortedList<TKey,TValue>需要一个要排序的比较器实现并执行比较。SortedList<TKey,TValue> requires a comparer implementation to sort and to perform comparisons. 默认比较器Comparer<T>.Default将检查键类型TKey是否实现System.IComparable<T>并使用该实现 (如果可用)。The default comparer Comparer<T>.Default checks whether the key type TKey implements System.IComparable<T> and uses that implementation, if available. 如果不是Comparer<T>.Default , 则检查键类型TKey是否System.IComparable实现。If not, Comparer<T>.Default checks whether the key type TKey implements System.IComparable. 如果键类型TKey未实现任何一个接口, 可以在接受comparer参数的System.Collections.Generic.IComparer<T>构造函数重载中指定实现。If the key type TKey does not implement either interface, you can specify a System.Collections.Generic.IComparer<T> implementation in a constructor overload that accepts a comparer parameter.

的容量SortedList<TKey,TValue>SortedList<TKey,TValue>可容纳的元素数。The capacity of a SortedList<TKey,TValue> is the number of elements the SortedList<TKey,TValue> can hold. 当向添加元素时SortedList<TKey,TValue>, 将根据需要通过重新分配内部数组来自动增加容量。As elements are added to a SortedList<TKey,TValue>, the capacity is automatically increased as required by reallocating the internal array. 可以通过调用TrimExcess或显式Capacity设置属性来减少容量。The capacity can be decreased by calling TrimExcess or by setting the Capacity property explicitly. 减少容量会重新分配内存, 并复制中SortedList<TKey,TValue>的所有元素。Decreasing the capacity reallocates memory and copies all the elements in the SortedList<TKey,TValue>.

仅 .NET Framework: 对于非常大SortedList<TKey,TValue>的对象, 可以通过在运行时环境中enabled<gcAllowVeryLargeObjects>配置元素的属性设置为true , 来将64位系统上的最大容量增加到2000000000个元素。.NET Framework only: For very large SortedList<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.

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. 由于的元素SortedList<TKey,TValue>是键/值对, 因此元素类型不是键的类型或值的类型。Since the elements of the SortedList<TKey,TValue> are key/value pairs, the element type is not the type of the key or the type of the value. 相反, 元素类型为KeyValuePair<TKey,TValue>Instead, the element type is KeyValuePair<TKey,TValue>. 例如:For example:

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

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

构造函数

SortedList<TKey,TValue>() SortedList<TKey,TValue>() SortedList<TKey,TValue>() SortedList<TKey,TValue>()

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

SortedList<TKey,TValue>(IComparer<TKey>) SortedList<TKey,TValue>(IComparer<TKey>) SortedList<TKey,TValue>(IComparer<TKey>) SortedList<TKey,TValue>(IComparer<TKey>)

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

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

初始化 SortedList<TKey,TValue> 类的新实例,该实例包含从指定的 IDictionary<TKey,TValue> 中复制的元素,其容量足以容纳所复制的元素数并使用默认的 IComparer<T>Initializes a new instance of the SortedList<TKey,TValue> class that contains elements copied from the specified IDictionary<TKey,TValue>, has sufficient capacity to accommodate the number of elements copied, and uses the default IComparer<T>.

SortedList<TKey,TValue>(IDictionary<TKey,TValue>, IComparer<TKey>) SortedList<TKey,TValue>(IDictionary<TKey,TValue>, IComparer<TKey>) SortedList<TKey,TValue>(IDictionary<TKey,TValue>, IComparer<TKey>) SortedList<TKey,TValue>(IDictionary<TKey,TValue>, IComparer<TKey>)

初始化 SortedList<TKey,TValue> 类的新实例,该实例包含从指定的 IDictionary<TKey,TValue> 中复制的元素,其容量足以容纳所复制的元素数并使用指定的 IComparer<T>Initializes a new instance of the SortedList<TKey,TValue> class that contains elements copied from the specified IDictionary<TKey,TValue>, has sufficient capacity to accommodate the number of elements copied, and uses the specified IComparer<T>.

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

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

SortedList<TKey,TValue>(Int32, IComparer<TKey>) SortedList<TKey,TValue>(Int32, IComparer<TKey>) SortedList<TKey,TValue>(Int32, IComparer<TKey>) SortedList<TKey,TValue>(Int32, IComparer<TKey>)

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

属性

Capacity Capacity Capacity Capacity

获取或设置 SortedList<TKey,TValue> 可包含的元素数。Gets or sets the number of elements that the SortedList<TKey,TValue> can contain.

Comparer Comparer Comparer Comparer

获取该排序列表的 IComparer<T>Gets the IComparer<T> for the sorted list.

Count Count Count Count

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

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

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

Keys Keys Keys Keys

获取一个按排序顺序包含 SortedList<TKey,TValue> 中的键的集合。Gets a collection containing the keys in the SortedList<TKey,TValue>, in sorted order.

Values Values Values Values

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

方法

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

将带有指定键和值的元素添加到 SortedList<TKey,TValue> 中。Adds an element with the specified key and value into the SortedList<TKey,TValue>.

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

SortedList<TKey,TValue> 中移除所有元素。Removes all elements from the SortedList<TKey,TValue>.

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

确定 SortedList<TKey,TValue> 是否包含特定键。Determines whether the SortedList<TKey,TValue> contains a specific key.

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

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

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()

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

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

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

(Inherited from Object)
GetType() GetType() GetType() GetType()

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

(Inherited from Object)
IndexOfKey(TKey) IndexOfKey(TKey) IndexOfKey(TKey) IndexOfKey(TKey)

在整个 SortedList<TKey,TValue> 中搜索指定键并返回从零开始的索引。Searches for the specified key and returns the zero-based index within the entire SortedList<TKey,TValue>.

IndexOfValue(TValue) IndexOfValue(TValue) IndexOfValue(TValue) IndexOfValue(TValue)

在整个 SortedList<TKey,TValue> 中搜索指定的值,并返回第一个匹配项的从零开始的索引。Searches for the specified value and returns the zero-based index of the first occurrence within the entire SortedList<TKey,TValue>.

MemberwiseClone() MemberwiseClone() MemberwiseClone() MemberwiseClone()

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

(Inherited from Object)
Remove(TKey) Remove(TKey) Remove(TKey) Remove(TKey)

SortedList<TKey,TValue> 中移除包含指定键的元素。Removes the element with the specified key from the SortedList<TKey,TValue>.

RemoveAt(Int32) RemoveAt(Int32) RemoveAt(Int32) RemoveAt(Int32)

移除 SortedList<TKey,TValue> 的指定索引处的元素。Removes the element at the specified index of the SortedList<TKey,TValue>.

ToString() ToString() ToString() ToString()

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

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

如果元素数小于当前容量的 90%,将容量设置为 SortedList<TKey,TValue> 中的实际元素数。Sets the capacity to the actual number of elements in the SortedList<TKey,TValue>, if that number is less than 90 percent of current capacity.

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 索引开始,将 Array 的元素复制到一个 Array 中。Copies the elements of the ICollection to an Array, starting at a particular Array index.

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

获取一个值,该值指示是否同步对 ICollection 的访问(线程安全)。Gets a value indicating 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 a key/value pair to the ICollection<T>.

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 element.

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> 索引开始,将 Array 的元素复制到一个 Array 中。Copies the elements of the ICollection<T> to an Array, starting at a particular Array index.

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

获取一个值,该值指示 ICollection<T> 是否为只读。Gets a value indicating whether the ICollection<T> 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>)

ICollection<T> 中移除特定键/值对的第一个匹配项。Removes the first occurrence of a specific key/value pair from the ICollection<T>.

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

IDictionary 中添加一个带有所提供的键和值的元素。Adds an element with the provided key and value to the IDictionary.

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 indicating whether the IDictionary has a fixed size.

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

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

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

获取或设置具有指定键的元素。Gets or sets the element 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 a 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 a collection.

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

获取包含只读字典中的密钥的可枚举集合。Gets an enumerable collection that contains the keys in the read-only dictionary.

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

获取包含只读字典中的值的可枚举集合。Gets an enumerable collection that contains the values in the read-only dictionary.

扩展方法

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.

适用于

线程安全性

此类型的Shared公共静态 (在 Visual Basic) 成员是线程安全的。Public static (Shared in Visual Basic) members of this type are thread safe. 但不保证所有实例成员都是线程安全的。Any instance members are not guaranteed to be thread safe.

只要不修改集合,就可以同时支持多个读取器。SortedList<TKey,TValue>A SortedList<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. 若要确保枚举过程中的线程安全性,可以在整个枚举过程中锁定集合。To guarantee thread safety during enumeration, you can lock the collection during the entire enumeration. 若要允许多个线程访问集合以进行读写操作,则必须实现自己的同步。To allow the collection to be accessed by multiple threads for reading and writing, you must implement your own synchronization.

另请参阅