1. 程式人生 > >C#入門泛型集合List<T>

C#入門泛型集合List<T>

div nbsp 需要 強制轉換 初始 cnblogs lsi 轉換 blog

泛型集合 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 }

C#入門泛型集合List<T>