c# ArrayList、List、Dictionary

ArrayList(频繁拆装箱等原因,消耗性能,不建议使用)

需引入的命名空间

using System.Collections;

 

使用

ArrayList arrayList = new ArrayList();arrayList.Add("abc");    //将数据新增到集合结尾处arrayList[0] = 123;    //修改指定索引处的数据arrayList.RemoveAt(0);    //移除指定索引处的数据arrayList.Remove(123);    //移除内容为123的数据arrayList.Insert(0, "abc"); //在指定索引处插入数据,原来的数据往后移,不会覆盖原来索引处数据

 

 

List集合(需要定义数据类型,添加的数据类型必须和定义的类型相同)

//方法一List<int> list = new List<int>();//方法二、初始化赋值List<int> list = new List<int>{ 1, 2, 3};list.Add(123);     //将数据新增到集合结尾处list.Add(789);list[0] = 456;     //修改指定索引处的数据list.RemoveAt(0);   //移除指定索引处的数据list.Remove(789);   //移除内容为123的数据list.Insert(0, 111); //在指定索引处插入数据,原来的数据往后移,不会覆盖原来索引处数据list.Clear();     //清空集合中所有数据foreach(int item in list){  Message.Show(item.ToString());}

 

 

 

Dictionary字典(需要给key,value定义类型,key要唯一,通过key获取value)

//方法一
Dictionary<int, string> keyValuePairs = new Dictionary<int, string>();keyValuePairs.Add(0, "张三"); //赋值keyValuePairs[5] = "王五"; //不会报错,如果有key=5的值则修改,如果没有则添加
方法二
//
初始化赋值Dictionary<string, string> keyValuePairs = new Dictionary<string, string>{ {"A","a"}, {"B","b"}};keyValuePairs["A"]="abc";keyValuePairs1.Remove("A"); //删除key="A"的数据string a = keyValuePairs1["A"]; //取值keyValuePairs1.Clear();        //清除所有数据//Dictionary使用foreach遍历KeyValuePair的类型与要遍历的key,value的类型要一致foreach (KeyValuePair<string,string> item in keyValuePairs){ string key = item.Key; string value = item.Value;}

 

 

 

自定义类型

先新建一个类

public class Person{ public int Age { get; set; } public string Name { get; set; }}

 

使用

List<Person> people = new List<Person>();  //不限于ListPerson person = new Person(){ Age = 18, Name = "张三"};people.Add(person);Person people1 = people[0];people.Remove(person1);

 

 

 

 

 

 
 
 
 
 
 

相关文章