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
Imports System.Collections
Imports Microsoft.VisualBasic

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的物件, 您可以在執行時間環境中, 將<gcAllowVeryLargeObjects> configuration 專案的enabled屬性設為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.

語言的foreach語句 (for each在 Visual Basic 中) 會傳回集合中元素類型的物件。 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 物件的淺層複本 (Shallow Copy)。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 的淺層複本 (Shallow Copy)。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()

傳回透過 IEnumerator 重複的 SortedListReturns 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.

只要不修改集合,物件就可以同時支援多個讀取器。SortedListA 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.

另請參閱