跳轉到內容

C# 程式設計/.NET 框架/集合

來自華夏公益教科書,開放的書籍,開放的世界

列表是動態陣列,可以根據需要調整自身大小,如果插入的資料量超過其插入時的容量。可以在任何索引處插入專案、在任何索引處刪除專案以及在任何索引處訪問專案。C# 的非泛型列表類是 ArrayList,而泛型列表類是 List<T>

以下示例演示了 List 類中的許多方法和屬性。

using System;
using System.Collections;
using System.Collections.Generic;

namespace csharp_generic_list
{
    class MainClass
    {
        public static void Main(string[] args)
        {
            Console.WriteLine("List<T> demo");
            // Creating an instance that accepts strings
            List<string> foods = new List<string>();

            // Adding some items one by one with Add()
            foods.Add("bread");
            foods.Add("butter");
            foods.Add("chocolate");

            // Adding a simple string array with AddRange()
            string[] subList1 = {"orange", "apple", "strawberry", "grapes", "kiwi", "banana"};
            foods.AddRange(subList1);

            // Adding another List<string> with AddRange()
            List<string> anotherFoodList = new List<string>();
            anotherFoodList.Add("yoghurt");
            anotherFoodList.Add("tomato");
            anotherFoodList.Add("roast beef");
            anotherFoodList.Add("vanilla cake");
            foods.AddRange(anotherFoodList);

            // Removing "orange" with Remove()
            foods.Remove("orange");

            // Removing the 5th (index = 4) item ("strawberry") with RemoveAt()
            foods.RemoveAt(4);

            // Removing a range (4-7: all fruits) with RemoveRange(int index, int count)
            foods.RemoveRange(3, 4);

            // sorting the list
            foods.Sort();

            // Printing the sorted foods
            foreach (string item in foods)
            {
                Console.Write("| " + item + " ");
            }
            Console.WriteLine("|");

            // Removing all items from foods
            foods.Clear();

            // Printing the current item count in foods
            Console.WriteLine("The list now has {0} items.", foods.Count);
        }
    }
}

終端輸出為

List<T> demo
| bread | butter | chocolate | roast beef | tomato | vanilla cake | yoghurt |
The list now has 0 items.

連結串列

[編輯 | 編輯原始碼]

連結串列中的專案只能按順序逐個訪問。當然,可以訪問任何索引處的專案,但列表必須從第一個專案開始迭代到該專案,這比在陣列或列表中按索引訪問專案要慢得多。C# 中沒有非泛型連結串列,而泛型連結串列是 LinkedList<T>

佇列是 FIFO(先進先出)集合。第一個推入佇列的專案將使用 pop 函式第一個彈出。在任何時候,只有第一個專案是可訪問的,並且專案只能放入末尾。非泛型佇列類稱為 Queue,而泛型佇列類是 Queue<T>

棧是 LIFO(後進先出)集合。第一個推入的專案將使用 pop 函式最後彈出。在任何時候,只有最後一個專案是可訪問的,並且專案只能放在頂部。非泛型棧類是 Stack,而泛型棧類是 Stack<T>

雜湊表和字典

[編輯 | 編輯原始碼]

字典是具有鍵值的集合。值可以非常複雜,但搜尋鍵仍然很快。非泛型類是 Hashtable,而泛型類是 Dictionary<TKey, TValue>

華夏公益教科書