首页 > 技术文章 > c# array arraylist 泛型list

yachao1120 2018-03-30 13:54 原文

1 array 数组  是存储相同类型元素的固定大小的数据的顺序集合。在内存中是连续存储的,所以索引速度非常快,而且赋值和修改元素也非常简单。

//定义字符串数组 大小为3
string[] str1 = new string[3];
str1[0] = "1";
str1[1] = "2";
str1[2] = "3";
//第二种赋值方式
string[] str2 = new string[] {"1","2","3" };
//第三种赋值方式
string[] str3 = { "1","2","3"};

2 arraylist对象的大小是按照其存储的数据来动态扩充的。声明arraylist对象不需要指定其长度。

//arraylist
ArrayList myal = new ArrayList();
myal.Add("HelloWorld");
myal.Add(12);
myal.Add(45.50);

arraylist可以存储不同类型的数据。装箱、拆箱特别麻烦。 arraylist会把所有插入的数据当做object对象来处理。

 

3 泛型 lsit<T> 数据类型是安全的,在声明list对象的时候,必须指定list集合内数据的对象类型.

List<string> myl = new List<string>();
myl.Add("123");

 

4 Dictionary  Dictionary<string, string>是一个泛型

他本身有集合的功能有时候可以把它看成数组

他的结构是这样的:Dictionary<[key], [value]>

他的特点是存入对象是需要与[key]值一一对应的存入该泛型

通过某一个一定的[key]去找到对应的值

举个例子:

//实例化对象

Dictionary<int, string> dic = new Dictionary<int, string>();

//对象打点添加

dic.Add(1, "one");

dic.Add(2, "two");

dic.Add(3, "one");

//提取元素的方法

string a = dic[1];

string b = dic[2];

string c = dic[3];

//1、2、3是键,分别对应“one”“two”“one”

//上面代码中分别把值赋给了a,b,c

//注意,键相当于找到对应值的唯一标识,所以不能重复

//但是值可以重复

 

list泛型的使用

ArrayList list = new ArrayList();
ArrayList list = new ArrayList(5); //可变数组
list.Add("我"); //Add 添加 向数组中赋值索引为最末尾
list.Add("今年");
list.Add("18");
list.Add("岁了");
list.Add("18");
list.Add("岁了");
list.Add("18");
list.Add("岁了");

知识点
list.Contains();//查询数组中元素是否存在
list.CopyTo(); //赋值数组中的全部数据
list.RemoveAt();//根据索引把指定位置元素删除
list.Remove(); //移除的是元素
list.Clear();//清空数组
list.Count; //数组元素的个数

举例子
bool result = list.Contains("我"); //返回bool 查询数组中元素是否存在

string[] list1 = new String[15];
list.CopyTo(list1); //赋值数组中的全部数据 赋值的集合的数据类型要一致

oblect[] list1 = new oblect[15];
list.CopyTo(list1); //赋值数组中的全部数据 赋值的集合的数据类型可以不一致

list.RemoveAt(6); //把第七个元素移除
list.Remove("我"); //移除的是元素

int index=list.Count;
Console.WriteLine(index);

Console.WriteLine(list[6]);

foreach (object val in list)
{
Console.WriteLine(val);
}
Console.ReadKey();
#endregion

#region 泛型集合
List<int> intList=new List<int>(); //List泛型集合 类型是一致的
intList.Add(12);
intList.Add(23);
intList.Add(34);
int result = intList.IndexOf(34);//根据元素,查找返回该元素的索引位置,如果没有,返回-1 可以指定索引范围(34,0,2)

//知识点
intList.Add();//查询数组中元素是否存在
intList.CopyTo(); //赋值数组中的全部数据
intList.RemoveAt();//根据索引把指定位置元素删除
intList.Remove(); //移除的是元素
intList.IndexOf(); //根据元素,查找返回该元素的索引位置,如果没有,返回-1
intList.Insert(1,16);//将元素插入集合某处

//举例子
intList[0] = 15;
intList.Insert(0,16);//将元素插入集合某处 原来索引位置的元素值自动下移,整理向后移动
Console.WriteLine(intList[0]);
Console.ReadKey();
#endregion

#region 泛型数组练习
List<string> arrList=new List<string>();
arrList.Add("张三");
arrList.Add("年龄");
arrList.Add("身高");
arrList.Add("电话号码");
int a = arrList.Count;
string name = "";
for (int i = 0; i < arrList.Count; i++)
{
if(arrList[0].Equals("张三"))
{
arrList[0] += "今年的";
Console.WriteLine(arrList[0]);
}
}
Console.ReadKey();

 

推荐阅读