在C#中,集合(Collection)是一组对象的容器,用于存储、检索和操作数据。C# 提供了多种内置的集合类型,每种类型都有其特定的用途和性能特性。以下是一些常用的C#集合类型:

1. 数组(Array):

数组是一种最简单的集合类型,用于存储固定大小的元素序列。
int[] numbers = new int[] { 1, 2, 3, 4, 5 };

2. 列表(List):

List<T> 是动态数组,可以根据需要动态调整大小。
List<int> numberList = new List<int> { 1, 2, 3, 4, 5 };

3. 集合(Collection):

Collection<T> 是一个抽象基类,可以派生出各种集合类型,如 List<T>。
Collection<int> numberCollection = new Collection<int> { 1, 2, 3, 4, 5 };

4. 字典(Dictionary):

Dictionary<TKey, TValue> 是一种键值对集合,通过键快速查找值。
Dictionary<string, int> keyValuePairs = new Dictionary<string, int>
{
    { "One", 1 },
    { "Two", 2 },
    { "Three", 3 }
};

5. 队列(Queue):

Queue<T> 是先进先出(FIFO)的集合。
Queue<string> queue = new Queue<string>();
queue.Enqueue("First");
queue.Enqueue("Second");

6. 栈(Stack):

Stack<T> 是后进先出(LIFO)的集合。
Stack<string> stack = new Stack<string>();
stack.Push("First");
stack.Push("Second");

7. 集合初始化器:

使用集合初始化器可以更简洁地初始化集合。
List<int> numbers = new List<int> { 1, 2, 3, 4, 5 };
Dictionary<string, int> keyValuePairs = new Dictionary<string, int>
{
    { "One", 1 },
    { "Two", 2 },
    { "Three", 3 }
};

这只是C#中一些常见的集合类型,还有其他更特定的集合类型,如 HashSet<T>、LinkedList<T> 等。选择合适的集合类型取决于你的具体需求和性能考虑。




转载请注明出处:http://www.pingtaimeng.com/article/detail/14774/C#