Latest web development tutorials

C# 排序列表(SortedList)

C# 集合 C#集合

SortedList類代表了一系列按照鍵來排序的鍵/值對,這些鍵值對可以通過鍵和索引來訪問。

排序列表是數組和哈希表的組合。 它包含一個可使用鍵或索引訪問各項的列表。 如果您使用索引訪問各項,則它是一個動態數組(ArrayList),如果您使用鍵訪問各項,則它是一個哈希表(Hashtable)。 集合中的各項總是按鍵值排序。

SortedList 類的方法和屬性

下表列出了SortedList類的一些常用的屬性

属性描述
Capacity 获取或设置 SortedList 的容量。
Count获取 SortedList 中的元素个数。
IsFixedSize获取一个值,表示 SortedList 是否具有固定大小。
IsReadOnly获取一个值,表示 SortedList 是否只读。
Item获取或设置与 SortedList 中指定的键相关的值。
Keys获取 SortedList 中的键。
Values获取 SortedList 中的值。

下表列出了SortedList類的一些常用的方法

序号方法名 & 描述
1public virtual void Add( object key, object value );
向 SortedList 添加一个带有指定的键和值的元素。
2public virtual void Clear();
从 SortedList 中移除所有的元素。
3public virtual bool ContainsKey( object key );
判断 SortedList 是否包含指定的键。
4public virtual bool ContainsValue( object value );
判断 SortedList 是否包含指定的值。
5public virtual object GetByIndex( int index );
获取 SortedList 的指定索引处的值。
6public virtual object GetKey( int index );
获取 SortedList 的指定索引处的键。
7public virtual IList GetKeyList();
获取 SortedList 中的键。
8public virtual IList GetValueList();
获取 SortedList 中的值。
9public virtual int IndexOfKey( object key );
返回 SortedList 中的指定键的索引,索引从零开始。
10public virtual int IndexOfValue( object value );
返回 SortedList 中的指定值第一次出现的索引,索引从零开始。
11public virtual void Remove( object key );
从 SortedList 中移除带有指定的键的元素。
12public virtual void RemoveAt( int index );
移除 SortedList 的指定索引处的元素。
13public virtual void TrimToSize();
设置容量为 SortedList 中元素的实际个数。

實例

下面的實例演示了排序列表(SortedList)的概念:

using System;
using System.Collections;

namespace CollectionsApplication
{
   class Program
   {
      static void Main(string[] args)
      {
         SortedList sl = new SortedList();

         sl.Add("001", "Zara Ali");
         sl.Add("002", "Abida Rehman");
         sl.Add("003", "Joe Holzner");
         sl.Add("004", "Mausam Benazir Nur");
         sl.Add("005", "M. Amlan");
         sl.Add("006", "M. Arif");
         sl.Add("007", "Ritesh Saikia");

         if (sl.ContainsValue("Nuha Ali"))
         {
            Console.WriteLine("This student name is already in the list");
         }
         else
         {
            sl.Add("008", "Nuha Ali");
         }

         // 獲取鍵的集合ICollection key = sl.Keys;

         foreach (string k in key)
         {
            Console.WriteLine(k + ": " + sl[k]);
         }
      }
   }
}

當上面的代碼被編譯和執行時,它會產生下列結果:

001: Zara Ali
002: Abida Rehman
003: Joe Holzner
004: Mausam Banazir Nur
005: M. Amlan 
006: M. Arif
007: Ritesh Saikia
008: Nuha Ali

C# 集合 C#集合