C Sharp/The .NET Framework/Collections

維基教科書,自由的教學讀本


Lists[編輯]

C#非泛型的list類是ArrayList,泛型類是List<T>

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.

LinkedLists[編輯]

訪問鍊表的元素,必須從頭部開始線性遍歷,因此會較慢。C#中有非泛型的鍊表,也有泛型的鍊表LinkedList<T>.

Queues[編輯]

隊列是先進先出的集合。非泛型的隊列是Queue,泛型的隊列是Queue<T>.

Stacks[編輯]

棧是後進先出的集合。非泛型的棧是Stack,泛型的棧是Stack<T>

Hashtables 與 dictionaries[編輯]

詞典是鍵值的集合。非泛型的類是Hashtable, 泛型的是Dictionary<TKey, TValue>.