集合的大小可以动态调整,可以在运行时添加或删除元素。集合可以通过索引访问集合成员,也可以通过“键”来访问。
集合分为泛型集合与非泛型集合
泛型集合类一般位于System.Collections.Generic
非泛型集合类位于System.Collections名称空间
非泛型集合
动态数组(ArrayList),堆栈(Stack),队列(Queue),哈希表(HashTable)
动态数组
动态的增加和减少元素
实现了ICollection和IList和IEnumerable接口
灵活的设置数组的大小
不安全的集合类型
其元素为值类型时,效率不高(装箱和拆箱耗性能)
using System;
using System.Collections;//引入命名空间namespace dArrayList
{
class Person {
}
class Program
{
static void Main(string[] args)
{
//实例化动态数组
ArrayList score = new ArrayList();
object value = new Person();
//向动态数组中添加元素
score.Add(90);
score.Add(85.5);
score.Add("English:100");
score[0] = 90;
//向动态数组中批量添加元素
int[] array = { 90, 80, 70 };
score.AddRange(array);
//向动态数组中插入元素
score.Insert(2,"Math:80.5");
//删除动态数组中的元素
score.Remove(85.5f);
score.Remove(90);//删除单个元素,如果没有该元素,就忽略
//根据下标移除动态数组中的元素
score.RemoveAt(0);
//批量删除元素
score.AddRange(new string[] { "A", "B", "C", "B", "C" });
score.RemoveRange(2, 3);
//数组元素翻转
score.Reverse();
//一般想要删除某个元素,先进行判断
bool containsA=score.Contains("A");
Console.WriteLine("ContainsA:" + containsA);
if (score.Contains("A")) {
score.Remove("A");
}
//清空动态数组
score.Clear();
foreach (var item in score) {
Console.WriteLine(item);
}
}
}
}