1. 程式人生 > >C#梳理【集合Collection】

C#梳理【集合Collection】

C# 集合(Collection)

集合(Collection)類是專門用於資料儲存和檢索的類。這些類提供了對棧(stack)、佇列(queue)、列表(list)和雜湊表(hash table)的支援。大多數集合類實現了相同的介面。

集合(Collection)類服務於不同的目的,如為元素動態分配記憶體,基於索引訪問列表項等等。這些類建立 Object 類的物件的集合。在 C# 中,Object 類是所有資料型別的基類。

各種集合類和它們的用法

下面是各種常用的 System.Collection 名稱空間的類。

描述和用法

動態陣列(ArrayList)                                                     
它代表了可被單獨索引的物件的有序集合。

它基本上可以替代一個數組。但是,與陣列不同的是,您可以使用索引在指定的位置新增和移除專案,動態陣列會自動重新調整它的大小。它也允許在列表中進行動態記憶體分配、增加、搜尋、排序各項。


雜湊表(Hashtable)
它使用來訪問集合中的元素。

當您使用鍵訪問元素時,則使用雜湊表,而且您可以識別一個有用的鍵值。雜湊表中的每一項都有一個鍵/值對。鍵用於訪問集合中的專案。


排序列表(SortedList)
它可以使用索引來訪問列表中的項。

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


堆疊(Stack)
它代表了一個後進先出的物件集合。

當您需要對各項進行後進先出的訪問時,則使用堆疊。當您在列表中新增一項,稱為推入元素,當您從列表中移除一項時,稱為彈出元素。


佇列(Queue)
它代表了一個先進先出的物件集合。

當您需要對各項進行先進先出的訪問時,則使用佇列。當您在列表中新增一項,稱為入隊,當您從列表中移除一項時,稱為出隊


點陣列(BitArray)
它代表了一個使用值 1 和 0 來表示的二進位制陣列。

當您需要儲存位,但是事先不知道位數時,則使用點陣列。您可以使用整型索引從點陣列集合中訪問各項,索引從零開始。

作為集合的補充,更多的原理和細節請參考文章:

C#常用資料結構的區別 。

C#動態陣列(ArrayList)

動態陣列(ArrayList)代表了可被單獨索引的物件的有序集合。它基本上可以替代一個數組。但是,與陣列不同的是,您可以使用索引在指定的位置新增和移除專案,動態陣列會自動重新調整它的大小。它也允許在列表中進行動態記憶體分配、增加、搜尋、排序各項。

ArrayList 類的方法和屬性

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

屬性 描述
Capacity 獲取或設定 ArrayList 可以包含的元素個數。
Count 獲取 ArrayList 中實際包含的元素個數。
IsFixedSize 獲取一個值,表示 ArrayList 是否具有固定大小。
IsReadOnly 獲取一個值,表示 ArrayList 是否只讀。
Item 獲取或設定指定索引處的元素。

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

序號 方法名 & 描述
1 public virtual int Add( object value ); 
在 ArrayList 的末尾新增一個物件。
2 public virtual void AddRange( ICollection c ); 
在 ArrayList 的末尾新增 ICollection 的元素。
3 public virtual void Clear();
從 ArrayList 中移除所有的元素。
4 public virtual bool Contains( object item ); 
判斷某個元素是否在 ArrayList 中。
5 public virtual ArrayList GetRange( int index, int count ); 
返回一個 ArrayList,表示源 ArrayList 中元素的子集。
6 public virtual int IndexOf(object);
返回某個值在 ArrayList 中第一次出現的索引,索引從零開始。
7 public virtual void Insert( int index, object value ); 
在 ArrayList 的指定索引處,插入一個元素。
8 public virtual void InsertRange( int index, ICollection c ); 
在 ArrayList 的指定索引處,插入某個集合的元素。
9 public virtual void Remove( object obj ); 
從 ArrayList 中移除第一次出現的指定物件。
10 public virtual void RemoveAt( int index ); 
移除 ArrayList 的指定索引處的元素。
11 public virtual void RemoveRange( int index, int count ); 
從 ArrayList 中移除某個範圍的元素。
12 public virtual void Reverse();
逆轉 ArrayList 中元素的順序。
13 public virtual void SetRange( int index, ICollection c ); 
複製某個集合的元素到 ArrayList 中某個範圍的元素上。
14 public virtual void Sort();
對 ArrayList 中的元素進行排序。
15 public virtual void TrimToSize();
設定容量為 ArrayList 中元素的實際個數。

ArrayList例項

下面的例項演示了動態陣列(ArrayList)的概念:

using System;
using System.Collections;

namespace CollectionApplication
{
    class Program
    {
        static void Main(string[] args)
        {
            ArrayList al = new ArrayList();

            Console.WriteLine("Adding some numbers:");
            al.Add(45);
            al.Add(78);
            al.Add(33);
            al.Add(56);
            al.Add(12);
            al.Add(23);
            al.Add(9);
            
            Console.WriteLine("Capacity: {0} ", al.Capacity);
            Console.WriteLine("Count: {0}", al.Count);
                      
            Console.Write("Content: ");
            foreach (int i in al)
            {
                Console.Write(i + " ");
            }
            Console.WriteLine();
            Console.Write("Sorted Content: ");
            al.Sort();
            foreach (int i in al)
            {
                Console.Write(i + " ");
            }
            Console.WriteLine();
            Console.ReadKey();
        }
    }
}

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

Adding some numbers:
Capacity: 8
Count: 7
Content: 45 78 33 56 12 23 9
Content: 9 12 23 33 45 56 78    

C# 雜湊表(Hashtable)

Hashtable 類代表了一系列基於鍵的雜湊程式碼組織起來的鍵/值對。它使用來訪問集合中的元素。

當您使用訪問元素時,則使用雜湊表,而且您可以識別一個有用的鍵值。雜湊表中的每一項都有一個鍵/值對。鍵用於訪問集合中的專案。

Hashtable 類的方法和屬性

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

屬性 描述
Count 獲取 Hashtable 中包含的鍵值對個數。
IsFixedSize 獲取一個值,表示 Hashtable 是否具有固定大小。
IsReadOnly 獲取一個值,表示 Hashtable 是否只讀。
Item 獲取或設定與指定的鍵相關的值。
Keys 獲取一個 ICollection,包含 Hashtable 中的鍵。
Values 獲取一個 ICollection,包含 Hashtable 中的值。

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

序號 方法名 & 描述
1 public virtual void Add( object key, object value ); 
向 Hashtable 新增一個帶有指定的鍵和值的元素。
2 public virtual void Clear(); 
從 Hashtable 中移除所有的元素。
3 public virtual bool ContainsKey( object key ); 
判斷 Hashtable 是否包含指定的鍵。
4 public virtual bool ContainsValue( object value ); 
判斷 Hashtable 是否包含指定的值。
5 public virtual void Remove( object key ); 
從 Hashtable 中移除帶有指定的鍵的元素。

Hashtable例項

下面的例項演示了雜湊表(Hashtable)的概念:

using System;
using System.Collections;

namespace CollectionsApplication
{
   class Program
   {
      static void Main(string[] args)
      {
         Hashtable ht = new Hashtable();
         ht.Add("001", "Zara Ali");
         ht.Add("002", "Abida Rehman");
         ht.Add("003", "Joe Holzner");
         ht.Add("004", "Mausam Benazir Nur");
         ht.Add("005", "M. Amlan");
         ht.Add("006", "M. Arif");
         ht.Add("007", "Ritesh Saikia");

         if (ht.ContainsValue("Nuha Ali"))
         {
            Console.WriteLine("This student name is already in the list");
         }
         else
         {
            ht.Add("008", "Nuha Ali");
         }
         // 獲取鍵的集合 
         ICollection key = ht.Keys;

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

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

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

C#排序列表(SortedList)

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

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

SortedList 類的方法和屬性

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

屬性 描述
Capacity 獲取或設定 SortedList 的容量。
Count 獲取 SortedList 中的元素個數。
IsFixedSize 獲取一個值,表示 SortedList 是否具有固定大小。
IsReadOnly 獲取一個值,表示 SortedList 是否只讀。
Item 獲取或設定與 SortedList 中指定的鍵相關的值。
Keys 獲取 SortedList 中的鍵。
Values 獲取 SortedList 中的值。

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

序號 方法名 & 描述
1 public virtual void Add( object key, object value ); 
向 SortedList 新增一個帶有指定的鍵和值的元素。
2 public virtual void Clear(); 
從 SortedList 中移除所有的元素。
3 public virtual bool ContainsKey( object key ); 
判斷 SortedList 是否包含指定的鍵。
4 public virtual bool ContainsValue( object value ); 
判斷 SortedList 是否包含指定的值。
5 public virtual object GetByIndex( int index ); 
獲取 SortedList 的指定索引處的值。
6 public virtual object GetKey( int index ); 
獲取 SortedList 的指定索引處的鍵。
7 public virtual IList GetKeyList(); 
獲取 SortedList 中的鍵。
8 public virtual IList GetValueList(); 
獲取 SortedList 中的值。
9 public virtual int IndexOfKey( object key ); 
返回 SortedList 中的指定鍵的索引,索引從零開始。
10 public virtual int IndexOfValue( object value ); 
返回 SortedList 中的指定值第一次出現的索引,索引從零開始。
11 public virtual void Remove( object key ); 
從 SortedList 中移除帶有指定的鍵的元素。
12 public virtual void RemoveAt( int index ); 
移除 SortedList 的指定索引處的元素。
13 public virtual void TrimToSize(); 
設定容量為 SortedList 中元素的實際個數。

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#堆疊(Stack)

堆疊(Stack)代表了一個後進先出的物件集合。當您需要對各項進行後進先出的訪問時,則使用堆疊。當您在列表中新增一項,稱為推入元素,當您從列表中移除一項時,稱為彈出元素。

Stack 類的方法和屬性

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

屬性 描述
Count 獲取 Stack 中包含的元素個數。

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

序號 方法名 & 描述
1 public virtual void Clear(); 
從 Stack 中移除所有的元素。
2 public virtual bool Contains( object obj ); 
判斷某個元素是否在 Stack 中。
3 public virtual object Peek();
返回在 Stack 的頂部的物件,但不移除它。
4 public virtual object Pop();
移除並返回在 Stack 的頂部的物件。
5 public virtual void Push( object obj );
向 Stack 的頂部新增一個物件。
6 public virtual object[] ToArray();
複製 Stack 到一個新的陣列中。

Stack例項

下面的例項演示了堆疊(Stack)的使用:

using System;
using System.Collections;

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

            st.Push('A');
            st.Push('M');
            st.Push('G');
            st.Push('W');
            
            Console.WriteLine("Current stack: ");
            foreach (char c in st)
            {
                Console.Write(c + " ");
            }
            Console.WriteLine();
            
            st.Push('V');
            st.Push('H');
            Console.WriteLine("The next poppable value in stack: {0}", 
            st.Peek());
            Console.WriteLine("Current stack: ");           
            foreach (char c in st)
            {
               Console.Write(c + " ");
            }
            Console.WriteLine();

            Console.WriteLine("Removing values ");
            st.Pop();
            st.Pop();
            st.Pop();
            
            Console.WriteLine("Current stack: ");
            foreach (char c in st)
            {
               Console.Write(c + " "); 
            }
        }
    }
}

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

Current stack: 
W G M A
The next poppable value in stack: H
Current stack: 
H V W G M A
Removing values
Current stack: 
G M A

C#佇列(Queue)

佇列(Queue)代表了一個先進先出的物件集合。當您需要對各項進行先進先出的訪問時,則使用佇列。當您在列表中新增一項,稱為入隊,當您從列表中移除一項時,稱為出隊


Queue 類的方法和屬性

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

屬性 描述
Count 獲取 Queue 中包含的元素個數。

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

序號 方法名 & 描述
1 public virtual void Clear(); 
從 Queue 中移除所有的元素。
2 public virtual bool Contains( object obj ); 
判斷某個元素是否在 Queue 中。
3 public virtual object Dequeue();
移除並返回在 Queue 的開頭的物件。
4 public virtual void Enqueue( object obj ); 
向 Queue 的末尾新增一個物件。
5 public virtual object[] ToArray();
複製 Queue 到一個新的陣列中。
6 public virtual void TrimToSize();
設定容量為 Queue 中元素的實際個數。

Queue例項

下面的例項演示了佇列(Queue)的使用:

using System;
using System.Collections;

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

         q.Enqueue('A');
         q.Enqueue('M');
         q.Enqueue('G');
         q.Enqueue('W');
         
         Console.WriteLine("Current queue: ");
         foreach (char c in q)
         Console.Write(c + " ");
         Console.WriteLine();
         q.Enqueue('V');
         q.Enqueue('H');
         Console.WriteLine("Current queue: ");         
         foreach (char c in q)
            Console.Write(c + " ");
         Console.WriteLine();
         Console.WriteLine("Removing some values ");
         char ch = (char)q.Dequeue();
         Console.WriteLine("The removed value: {0}", ch);
         ch = (char)q.Dequeue();
         Console.WriteLine("The removed value: {0}", ch);
         Console.ReadKey();
      }
   }
}

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

Current queue: 
A M G W 
Current queue: 
A M G W V H 
Removing values
The removed value: A
The removed value: M

C#點陣列(BitArray)