泛型集合 List<T>
List<T>泛型集合特点:
- <T>表示泛型,T是Type简写,表示当前不确定具体类型;
- 可以根据用户的实际需要,确定当前集合需要存放的数据类型,一旦确定不可改变;
- 使用泛型集合只能添加一种类型的数据,数据取出后无需强制转换
1 static void Main(string[] args) 2 { 3 //创建几个学员对象 4 Student objStudent1 = new Student(1001, "小明"); 5 Student objStudent2 = new Student(1002, "小王"); 6 Student objStudent3 = new Student(1003, "小林"); 7 Student objStudent4 = new Student(1004, "小周"); 8 Student objStudent5 = new Student(1005, "小郭"); 9 10 //创建集合对象 11 List<Student> objStuList = new List<Student>(); 12 objStuList.Add(objStudent1); 13 objStuList.Add(objStudent2); 14 objStuList.Add(objStudent3); 15 objStuList.Add(objStudent4); 16 objStuList.Add(objStudent5); 17 //利用对象初始化器来添加对象 18 objStuList.Add(new Student() 19 { 20 StudentId = 1009, 21 StudentName = "linxinzhao" 22 }); 23 24 //Teacher objTeacher = new Teacher() { TeacherId=9001,TeacherName="andy 老师"}; 25 26 //获取元素个数 27 Console.WriteLine("元素总数:{0}", objStuList.Count); 28 //删除一个元素 remove 29 objStuList.Remove(objStudent4); 30 objStuList.RemoveAt(0); 31 //插入一个对象 32 objStuList.Insert(0, new Student(1006, "xiao")); 33 //遍历集合 34 foreach (var item in objStuList) 35 { 36 Console.WriteLine(item.StudentName + "\t" + item.StudentId); 37 } 38 //使用集合初始化器初始化泛型集合 39 List<Student> stuLsit = new List<Student>() { objStudent1, objStudent2, objStudent3, objStudent4 }; 40 List<string> strNameList = new List<string>() { "list1", "list2", "list3" }; 41 //使用for循环遍历 42 for (int i = 0; i < strNameList.Count; i++) 43 { 44 Console.WriteLine(strNameList[i]); 45 } 46 Console.ReadLine(); 47 }
时间: 2024-10-28 19:04:22