SortedList SortedList SortedList SortedList Class

定义

表示键/值对的集合,这些键值对按键排序并可按照键和索引访问。Represents a collection of key/value pairs that are sorted by the keys and are accessible by key and by index.

public ref class SortedList : ICloneable, System::Collections::IDictionary
[System.Runtime.InteropServices.ComVisible(true)]
[System.Serializable]
public class SortedList : ICloneable, System.Collections.IDictionary
type SortedList = class
    interface IDictionary
    interface ICloneable
    interface ICollection
    interface IEnumerable
Public Class SortedList
Implements ICloneable, IDictionary
继承
SortedListSortedListSortedListSortedList
属性
实现

示例

下面的代码示例演示如何创建和初始化SortedList对象, 以及如何输出对象的键和值。The following code example shows how to create and initialize a SortedList object and how to print out its keys and values.

#using <system.dll>

using namespace System;
using namespace System::Collections;
public ref class SamplesSortedList
{
public:
   static void PrintKeysAndValues( SortedList^ myList )
   {
      Console::WriteLine( "\t-KEY-\t-VALUE-" );
      for ( int i = 0; i < myList->Count; i++ )
      {
         Console::WriteLine( "\t{0}:\t{1}", myList->GetKey( i ), myList->GetByIndex( i ) );

      }
      Console::WriteLine();
   }

};

int main()
{

   // Creates and initializes a new SortedList.
   SortedList^ mySL = gcnew SortedList;
   mySL->Add( "Third", "!" );
   mySL->Add( "Second", "World" );
   mySL->Add( "First", "Hello" );

   // Displays the properties and values of the SortedList.
   Console::WriteLine( "mySL" );
   Console::WriteLine( "  Count:    {0}", mySL->Count );
   Console::WriteLine( "  Capacity: {0}", mySL->Capacity );
   Console::WriteLine( "  Keys and Values:" );
   SamplesSortedList::PrintKeysAndValues( mySL );
}

/*
This code produces the following output.

mySL
Count:    3
Capacity: 16
Keys and Values:
-KEY-    -VALUE-
First:    Hello
Second:    World
Third:    !
*/
using System;
using System.Collections;
public class SamplesSortedList  {

   public static void Main()  {

      // Creates and initializes a new SortedList.
      SortedList mySL = new SortedList();
       mySL.Add("Third", "!");
       mySL.Add("Second", "World");
       mySL.Add("First", "Hello");

      // Displays the properties and values of the SortedList.
      Console.WriteLine( "mySL" );
      Console.WriteLine( "  Count:    {0}", mySL.Count );
      Console.WriteLine( "  Capacity: {0}", mySL.Capacity );
      Console.WriteLine( "  Keys and Values:" );
      PrintKeysAndValues( mySL );
   }


   public static void PrintKeysAndValues( SortedList myList )  {
      Console.WriteLine( "\t-KEY-\t-VALUE-" );
      for ( int i = 0; i < myList.Count; i++ )  {
         Console.WriteLine( "\t{0}:\t{1}", myList.GetKey(i), myList.GetByIndex(i) );
      }
      Console.WriteLine();
   }
}
/*
This code produces the following output.

mySL
  Count:    3
  Capacity: 16
  Keys and Values:
    -KEY-    -VALUE-
    First:    Hello
    Second:    World
    Third:    !
*/
Imports System.Collections

Public Class SamplesSortedList    
    
    Public Shared Sub Main()
        
        ' Creates and initializes a new SortedList.
        Dim mySL As New SortedList()
        mySL.Add("Third", "!")
        mySL.Add("Second", "World")
        mySL.Add("First", "Hello")
        
        ' Displays the properties and values of the SortedList.
        Console.WriteLine("mySL")
        Console.WriteLine("  Count:    {0}", mySL.Count)
        Console.WriteLine("  Capacity: {0}", mySL.Capacity)
        Console.WriteLine("  Keys and Values:")
        PrintKeysAndValues(mySL)
    End Sub
    
    Public Shared Sub PrintKeysAndValues(myList As SortedList)
        Console.WriteLine(ControlChars.Tab & "-KEY-" & ControlChars.Tab & _
           "-VALUE-")
        Dim i As Integer
        For i = 0 To myList.Count - 1
            Console.WriteLine(ControlChars.Tab & "{0}:" & ControlChars.Tab & _
               "{1}", myList.GetKey(i), myList.GetByIndex(i))
        Next i
        Console.WriteLine()
    End Sub
End Class

' This code produces the following output.
' 
' mySL
'   Count:    3
'   Capacity: 16
'   Keys and Values:
'     -KEY-     -VALUE-
'     First:    Hello
'     Second:   World
'     Third:    !
 

注解

可以通过IDictionary IList元素的键 (如任何实现中的元素) 或其索引 (如任何实现中的元素) 访问元素。 SortedListA SortedList element can be accessed by its key, like an element in any IDictionary implementation, or by its index, like an element in any IList implementation.

重要

不建议使用SortedList类进行新的开发。We don't recommend that you use the SortedList class for new development. 相反, 我们建议使用泛型System.Collections.Generic.SortedList<TKey,TValue>类。Instead, we recommend that you use the generic System.Collections.Generic.SortedList<TKey,TValue> class. 有关详细信息, 请参阅 GitHub 上不应使用非泛型集合For more information, see Non-generic collections shouldn't be used on GitHub.

SortedList对象在内部维护两个用于存储列表元素的数组; 即, 一个数组用于存储键, 另一个数组用于关联值。A SortedList object internally maintains two arrays to store the elements of the list; that is, one array for the keys and another array for the associated values. 每个元素都是一个可作为DictionaryEntry对象进行访问的键/值对。Each element is a key/value pair that can be accessed as a DictionaryEntry object. 键不能为null, 但值可以为。A key cannot be null, but a value can be.

SortedList对象的容量是SortedList可容纳的元素数。The capacity of a SortedList object is the number of elements the SortedList can hold. 向添加元素时SortedList, 会根据需要通过重新分配来自动增加容量。As elements are added to a SortedList, the capacity is automatically increased as required through reallocation. 可以通过调用TrimToSize或显式Capacity设置属性来减少容量。The capacity can be decreased by calling TrimToSize or by setting the Capacity property explicitly.

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

SortedList对象的元素根据创建时SortedList指定的特定IComparer实现进行排序, 或根据IComparable键本身提供的实现进行排序。The elements of a SortedList object are sorted by the keys either according to a specific IComparer implementation specified when the SortedList is created or according to the IComparable implementation provided by the keys themselves. 在任一情况下, SortedList都不允许使用重复键。In either case, a SortedList does not allow duplicate keys.

索引顺序基于排序顺序。The index sequence is based on the sort sequence. 添加元素时, 该元素SortedList以正确的排序顺序插入, 并且索引会相应地进行调整。When an element is added, it is inserted into SortedList in the correct sort order, and the indexing adjusts accordingly. 删除元素时, 索引编制还会相应地进行调整。When an element is removed, the indexing also adjusts accordingly. 因此, 当在SortedList对象中添加或删除元素时, 特定键/值对的索引可能会更改。Therefore, the index of a specific key/value pair might change as elements are added or removed from the SortedList object.

由于排序, SortedList对对象的操作往往比Hashtable对象上的操作慢。Operations on a SortedList object tend to be slower than operations on a Hashtable object because of the sorting. 但是, 通过SortedList允许通过关联的键或索引来访问值, 可以提供更大的灵活性。However, the SortedList offers more flexibility by allowing access to the values either through the associated keys or through the indexes.

可以使用整数索引访问此集合中的元素。Elements in this collection can be accessed using an integer index. 此集合中的索引从零开始。Indexes in this collection are zero-based.

语言的for each语句 (在 Visual Basic 中) 返回集合中元素的类型的对象。 foreach C#The foreach statement of the C# language (for each in Visual Basic) returns an object of the type of the elements in the collection. 由于SortedList对象的每个元素都是键/值对, 因此元素类型不是键的类型或值的类型。Since each element of the SortedList object is a key/value pair, the element type is not the type of the key or the type of the value. 相反, 元素类型为DictionaryEntryRather, the element type is DictionaryEntry. 例如:For example:

for each (DictionaryEntry de in mySortedList)
{
    //...
}
foreach (DictionaryEntry de in mySortedList)
{
    //...
}
For Each de As DictionaryEntry In mySortedList
    '...
Next de

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

构造函数

SortedList() SortedList() SortedList() SortedList()

初始化 SortedList 类的新实例,该实例为空、具有默认初始容量并根据 IComparable 接口(此接口由添加到 SortedList 对象中的每个键实现)进行排序。Initializes a new instance of the SortedList class that is empty, has the default initial capacity, and is sorted according to the IComparable interface implemented by each key added to the SortedList object.

SortedList(IComparer) SortedList(IComparer) SortedList(IComparer) SortedList(IComparer)

初始化 SortedList 类的新实例,该实例为空、具有默认初始容量并根据指定的 IComparer 接口进行排序。Initializes a new instance of the SortedList class that is empty, has the default initial capacity, and is sorted according to the specified IComparer interface.

SortedList(IComparer, Int32) SortedList(IComparer, Int32) SortedList(IComparer, Int32) SortedList(IComparer, Int32)

初始化 SortedList 类的新实例,该实例为空、具有指定的初始容量并根据指定的 IComparer 接口排序。Initializes a new instance of the SortedList class that is empty, has the specified initial capacity, and is sorted according to the specified IComparer interface.

SortedList(IDictionary) SortedList(IDictionary) SortedList(IDictionary) SortedList(IDictionary)

初始化 SortedList 类的新实例,该实例包含从指定字典复制的元素、具有与所复制的元素数相同的初始容量并根据由每个键实现的 IComparable 接口排序。Initializes a new instance of the SortedList class that contains elements copied from the specified dictionary, has the same initial capacity as the number of elements copied, and is sorted according to the IComparable interface implemented by each key.

SortedList(IDictionary, IComparer) SortedList(IDictionary, IComparer) SortedList(IDictionary, IComparer) SortedList(IDictionary, IComparer)

初始化 SortedList 类的新实例,该实例包含从指定字典复制的元素、具有与所复制的元素数相同的初始容量并根据指定的 IComparer 接口排序。Initializes a new instance of the SortedList class that contains elements copied from the specified dictionary, has the same initial capacity as the number of elements copied, and is sorted according to the specified IComparer interface.

SortedList(Int32) SortedList(Int32) SortedList(Int32) SortedList(Int32)

初始化 SortedList 类的新实例,该实例为空、具有指定的初始容量并且根据 IComparable 接口(此接口由添加到 SortedList 对象的每个键实现)进行排序。Initializes a new instance of the SortedList class that is empty, has the specified initial capacity, and is sorted according to the IComparable interface implemented by each key added to the SortedList object.

属性

Capacity Capacity Capacity Capacity

获取或设置 SortedList 对象的容量。Gets or sets the capacity of a SortedList object.

Count Count Count Count

获取 SortedList 对象中包含的元素数。Gets the number of elements contained in a SortedList object.

IsFixedSize IsFixedSize IsFixedSize IsFixedSize

获取一个值,该值指示 SortedList 对象是否具有固定大小。Gets a value indicating whether a SortedList object has a fixed size.

IsReadOnly IsReadOnly IsReadOnly IsReadOnly

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

IsSynchronized IsSynchronized IsSynchronized IsSynchronized

获取一个值,该值指示对 SortedList 对象的访问是否同步(线程安全)。Gets a value indicating whether access to a SortedList object is synchronized (thread safe).

Item[Object] Item[Object] Item[Object] Item[Object]

获取或设置与 SortedList 对象中的特定键相关联的值。Gets or sets the value associated with a specific key in a SortedList object.

Keys Keys Keys Keys

获取 SortedList 对象中的键。Gets the keys in a SortedList object.

SyncRoot SyncRoot SyncRoot SyncRoot

获取一个对象,该对象可用于同步对 SortedList 对象的访问。Gets an object that can be used to synchronize access to a SortedList object.

Values Values Values Values

获取 SortedList 对象中的值。Gets the values in a SortedList object.

方法

Add(Object, Object) Add(Object, Object) Add(Object, Object) Add(Object, Object)

将带有指定键和值的元素添加到 SortedList 对象。Adds an element with the specified key and value to a SortedList object.

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

SortedList 对象中移除所有元素。Removes all elements from a SortedList object.

Clone() Clone() Clone() Clone()

创建 SortedList 对象的浅表副本。Creates a shallow copy of a SortedList object.

Contains(Object) Contains(Object) Contains(Object) Contains(Object)

确定 SortedList 对象是否包含特定键。Determines whether a SortedList object contains a specific key.

ContainsKey(Object) ContainsKey(Object) ContainsKey(Object) ContainsKey(Object)

确定 SortedList 对象是否包含特定键。Determines whether a SortedList object contains a specific key.

ContainsValue(Object) ContainsValue(Object) ContainsValue(Object) ContainsValue(Object)

确定 SortedList 对象是否包含特定值。Determines whether a SortedList object contains a specific value.

CopyTo(Array, Int32) CopyTo(Array, Int32) CopyTo(Array, Int32) CopyTo(Array, Int32)

从指定数组索引开始将 SortedList 元素复制到一维 Array 对象中。Copies SortedList elements to a one-dimensional Array object, starting at the specified index in the array.

Equals(Object) Equals(Object) Equals(Object) Equals(Object)

确定指定的对象是否等于当前对象。Determines whether the specified object is equal to the current object.

(Inherited from Object)
GetByIndex(Int32) GetByIndex(Int32) GetByIndex(Int32) GetByIndex(Int32)

获取 SortedList 对象的指定索引处的值。Gets the value at the specified index of a SortedList object.

GetEnumerator() GetEnumerator() GetEnumerator() GetEnumerator()

返回一个循环访问 IDictionaryEnumerator 对象的 SortedList 对象。Returns an IDictionaryEnumerator object that iterates through a SortedList object.

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

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

(Inherited from Object)
GetKey(Int32) GetKey(Int32) GetKey(Int32) GetKey(Int32)

获取 SortedList 对象的指定索引处的键。Gets the key at the specified index of a SortedList object.

GetKeyList() GetKeyList() GetKeyList() GetKeyList()

获取 SortedList 对象中的键。Gets the keys in a SortedList object.

GetType() GetType() GetType() GetType()

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

(Inherited from Object)
GetValueList() GetValueList() GetValueList() GetValueList()

获取 SortedList 对象中的值。Gets the values in a SortedList object.

IndexOfKey(Object) IndexOfKey(Object) IndexOfKey(Object) IndexOfKey(Object)

返回 SortedList 对象中指定键的从零开始的索引。Returns the zero-based index of the specified key in a SortedList object.

IndexOfValue(Object) IndexOfValue(Object) IndexOfValue(Object) IndexOfValue(Object)

返回指定的值在 SortedList 对象中第一个匹配项的从零开始的索引。Returns the zero-based index of the first occurrence of the specified value in a SortedList object.

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

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

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

SortedList 对象中移除带有指定键的元素。Removes the element with the specified key from a SortedList object.

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

移除 SortedList 对象的指定索引处的元素。Removes the element at the specified index of a SortedList object.

SetByIndex(Int32, Object) SetByIndex(Int32, Object) SetByIndex(Int32, Object) SetByIndex(Int32, Object)

替换 SortedList 对象中指定索引处的值。Replaces the value at a specific index in a SortedList object.

Synchronized(SortedList) Synchronized(SortedList) Synchronized(SortedList) Synchronized(SortedList)

返回 SortedList 对象的同步(线程安全)包装。Returns a synchronized (thread-safe) wrapper for a SortedList object.

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

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

(Inherited from Object)
TrimToSize() TrimToSize() TrimToSize() TrimToSize()

将容量设置为 SortedList 对象中元素的实际数目。Sets the capacity to the actual number of elements in a SortedList object.

显式界面实现

IEnumerable.GetEnumerator() IEnumerable.GetEnumerator() IEnumerable.GetEnumerator() IEnumerable.GetEnumerator()

返回循环访问 IEnumeratorSortedListReturns an IEnumerator that iterates through the SortedList.

扩展方法

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.

适用于

线程安全性

此类型的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对象可以同时支持多个读取器, 只要不修改该集合。A SortedList object can support multiple readers concurrently, as long as the collection is not modified. 若要保证的线程安全SortedList, 必须通过Synchronized(SortedList)方法返回的包装执行所有操作。To guarantee the thread safety of the SortedList, all operations must be done through the wrapper returned by the Synchronized(SortedList) method.

枚举整个集合本质上不是一个线程安全的过程。Enumerating through a collection is intrinsically not a thread-safe procedure. 即使某个集合已同步,其他线程仍可以修改该集合,这会导致枚举数引发异常。Even when a collection is synchronized, other threads can still modify the collection, which causes the enumerator to throw an exception. 若要确保枚举过程中的线程安全性,可以在整个枚举期间锁定集合,或者捕获由其他线程进行的更改所导致的异常。To guarantee thread safety during enumeration, you can either lock the collection during the entire enumeration or catch the exceptions resulting from changes made by other threads.

另请参阅