数据集合
数组
定义数组
int[] arrayA = new int[5];
int[] arrayB = new int[] { 1, 2, 3, 4, 5 };
int[] arrayC = new int[5] { 1, 2, 3, 4, 5 };
ArrayList
ArrayList的增删查改
ArrayList arrayList = new ArrayList();
// 添加元素
arrayList.Add("123");
arrayList.Add("abc");
arrayList.Add("uuu");
arrayList.Add("iii");
// 在指定位置加入元素
arrayList.Insert(1, "zzz");
// 根据索引删除元素
arrayList.RemoveAt(2);
// 删除元素
arrayList.Remove("123");
// 遍历
foreach (variteminarrayList)
{
Console.WriteLine(item);
}
ArrayList 的劣势
- ArrayList 存储数据使用 object 类型进行存储。
- ArrayList 不是类型安全的,使用时很可能出现类型不匹配的错误。
- 当插入式 int 类型,存储时会转换为 object 类型
- ArrayList 插入同一类型的数据,在使用时,也要转换为原数据类型来处理
- ArrayList 的存储是在装箱和拆箱操作,导致其性能低下
- 装箱:原类型转为 object 类型
- 拆箱:object 类型转为原类型
List
List的增删查改
List<string> strList = newList<string>();
// 添加元素
strList.Add("aaa");
strList.Add("bbb");
strList.Add("ccc");
strList.Add("ddd");
// 在指定位置插入元素
strList.Insert(2, "qqq");
// 删除元素
strList.Remove("ccc");
strList.RemoveAt(0);
// 修改元素
strList[1] = "kkk";
// 清除List
strList.Clear();
字典 Dictionary
声明 Dictionary 时,需要同时声明字典的 键 和 值 的类型;
键和值可以任意类型,键是唯一的,值可以不唯一;
字典的增删查改
Dictionary<int, string> d1 = new Dictionary<int, string>();
d1.Add(0, "aaa");
d1.Add(1, "bbb");
d1.Add(2, "ccc");
//根据键重新赋值
d1[1] = "ttt";
//如果键不存在,则添加入字典中
d1[3] = "ddd";
//根据键删除值
d1.Remove(2);
//foreach遍历
foreach (var item in d1)
{
Console.WriteLine(item);
}
foreach (KeyValuePair<int, string> itemind1)
{
Console.WriteLine(item);
}