C Sharp/The .NET Framework/Collections


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>.