List<T>
1、什么是泛型?
泛型就是程序的一种特性,用于限定程序的类型。string[]、int[]等基础数据类型和自定义类型都是确定类型的。
2、为什么要使用集合?
数组在定义是需要明确元素个数,在程序开发中,若是在声明变量时,不确定元素格式,使用数组可能会存在冗余和超出数组界限的情况,集合的声明不需要考虑元素的个数,根据实际的设计需要自动增长。
3、常用集合方法
List<string> nameList = new List<string>
{
"张三","李四","王五","赵六"
};
//添加元素
nameList.Add("王麻子");
//在指定位置插入元素
nameList.Insert(0, "老蔡");//在首位插入元素
nameList.Insert(4, "老吴");//在索引为4的元素前插入一个新的元素
//集合元素个数
int count= nameList.Count();
//查找元素对象
bool reslut= nameList.Contains("张三");//查找这个元素是否在集合中
//移除对象
nameList.Remove("王麻子");
nameList.RemoveAt(2);
nameList.Clear();
集合的复制
tlist和nameList指向的地址是一致的,会随着nameList内容的改变而改变,引用地址相同。
nlist和nameList是两个不同引用地址,不会随着nameList内容的改变而改变。nlist在new List<string>(nameList)这里,首先对申请了一段内存空间,然后把nameList的内容复制到这段内存空间中去
List<string> nameList = new List<string>
{
"张三","李四","王五","赵六"
};
List<string> tlist = nameList;
List<string> nlist = new List<string>(nameList);
常用的方法还有ToArray();
LINQ查询泛型集合的内容
//LINQ查询集合对象
List<Student> studentsList = new List<Student>()
{
new Student(){Sex="男",StuName="张三",StuID=155154,Age=19},
new Student(){Sex="男",StuName="张思",StuID=155185,Age=29},
} ;
Student student= studentsList.Where(c => c.StuName == "张三").First();
Dictionary<TKey, TValue>
PS:一般情况下TKey用string类型情况比较多,而TValue一般情况下,使用对象类型比较多(普通对象,集合对象)
Student student1 = new Student() { Sex = "男", StuName = "赵6", StuID = 155186, Age = 39 };
Student student2 = new Student() { Sex = "男", StuName = "赵7", StuID = 155189, Age = 9 };
Dictionary<string, Student> studentDic = new Dictionary<string, Student>()
{
["赵6"] = student1,
["赵7"] = student2,
};
Tkey键值需要加[] 。获取TValue的值=》 实例名["键值内容"],studentDic["张三"]
Dictionary字典可以把Value值转换成泛型集合
List<Student> list=studentDic.Values.ToList();//Value转换成list,需要注意的是list集合的类型要与TValue声明的类型一致
Dictionary的Tkey,TValue的值可以分别的分别遍历,在实际开发中,通过这个可以获取到一定好处。
小结:Dictionary<Tkey,Tvalue>和泛型集合List<T>本质上都是对数据(对象)的存储,是数据对象的容器。