Generic collection list<t>
List<t> Generic Collection features:
- <T> represents generics, T is a type shorthand, indicating that the specific type is currently indeterminate;
- According to the actual needs of the user, the current collection needs to determine the type of data to be stored, once the determination is not changed;
- only one type of data can be added using a generic collection, and no casting is required after the data is taken out
1 static void Main (string[] args)
2 {
3 //Create several learner objects4Student objStudent1 =NewStudent (1001,"Xiao Ming");5Student ObjStudent2 =NewStudent (1002,"Xiao Wang");6Student ObjStudent3 =NewStudent (1003,"Xiao Lin");7Student objStudent4 =NewStudent (1004,"Small weeks");8Student OBJSTUDENT5 =NewStudent (1005,"Xiao Guo");9 Ten //To create a collection object OneList<student> objstulist =NewList<student>();
A Objstulist.add (objStudent1); - Objstulist.add (objStudent2); - Objstulist.add (OBJSTUDENT3); the Objstulist.add (OBJSTUDENT4); - Objstulist.add (OBJSTUDENT5); - //use object initializers to add Objects -Objstulist.add (NewStudent () + { -StudentID =1009, +Studentname ="Linxinzhao" A }); at - //Teacher objteacher = new Teacher () {teacherid=9001,teachername= "Andy Teacher"}; - - //get the number of elements -Console.WriteLine ("Total elements: {0}", objstulist.count); - //Remove an element remove in Objstulist.remove (OBJSTUDENT4); -Objstulist.removeat (0); to //Insert an Object +Objstulist.insert (0,NewStudent (1006,"Xiao")); - //iterating through the collection the foreach(varIteminchobjstulist) * { $Console.WriteLine (item. Studentname +"\ t"+item. StudentID);Panax Notoginseng } - //initializing a generic collection using the collection initializer theList<student> stulsit =NewList<student>() {objStudent1, ObjStudent2, ObjStudent3, objStudent4}; +list<string> strnamelist =Newlist<string> () {"List1","List2","List3" }; A //use for loop traversal the for(inti =0; i < Strnamelist.count; i++) + { - Console.WriteLine (Strnamelist[i]); $ } $ console.readline (); -}
C # Getting Started generic collection list<t>