1, generic type list<t>
Generic List<t>, where T is a custom data type
List<int> list=new list<int> ();
List. ADD (121);
The Add () method is used to add elements of the appropriate type.
Exercise 1:
//combine the two sets to remove duplicates into one. list<int> Listone =Newlist<int> () {1,2,3,4,5,6 }; List<int> listtwo =Newlist<int> () {2,3,4,5,6, + };//loop Listone To determine if the element contains listtwo elements for(inti =0; i < Listone.count; i++){ //the Listone element is not added to the listtwo when it is not included in Listtwo if(!listtwo.contains (Listone[i])) {Listtwo.add (listone[i]); }} for(inti =0; i < Listtwo.count; i++) {Console.WriteLine (Listtwo[i]);}
Exercise 2:
//randomly generated numbers between 10 and 1-100 are placed in the list, requiring that the 10 numbers cannot be duplicated, and are all even (add 10 times, possibly looping many times.) ) //thought: All is even is the judge condition; Number 10, first create a list of 10 elementslist<int> listint =Newlist<int>(); Listint.add (2); Random R=NewRandom (); while(Listint.count! =Ten)//when Count reaches 10 is not established, no longer enters the loop; or with a count<10 { intnum = R.next (1,101);//randomly generated numbers//determine when NUM is not included in the Listint and is an even number added in if(!listint.contains (num) && num%2==0) {listint.add (num); } } for(inti =0; i < Listint.count; i++) {Console.WriteLine (listint[i]); }
2, Set dictionary
Dictionary<key,value>
Dictionary and generics also add elements using the Add () method
Key-value pairs typically use a foreach traversal
Exercise 1
dictionary<int,string> dics =Newdictionary<int,string>(); Dics. ADD (1," One"); Dics. ADD (2,"franchised"); Dics. ADD (3,"three"); Dics. ADD (4,"Restaurant"); //key-value pairs typically traverse through a foreach
//foreach (int item in dics. Keys)//{ //Console.WriteLine (item); //} //foreach (String item in Dics. Values)//{ //Console.WriteLine (item); //} //traversing keys and values at the same time foreach(keyvaluepair<int,string> Iteminchdics) {Console.WriteLine (item. Key+"=="+item. Value); }
Exercise 2
//convert input number to uppercase stringstr ="1 2 franchised 3 three 4 establishments 5 Wu Lu 6 seven 7 BA 8 JIU"; string[] txts = str. Split (New Char[] {' '}, Stringsplitoptions.removeemptyentries); Dictionary<int,Char> dic =Newdictionary<int,Char>(); for(inti =0; I < txts. Length; i++) { if(!dic. ContainsKey (txts[i][0]))//if TXTS[I][0] is not included in the DIC key, add in{dic. ADD (txts[i][0], txts[i][1]); }} Console.WriteLine ("Please enter a number"); stringmsg =Console.ReadLine (); for(inti =0; I < Msg. Length; i++) { if(DIC. ContainsKey (Msg[i]))//If the user enters a number that is contained in the collection, the value displayed for{Console.Write (dic[msg[i]); } Else{Console.Write (msg[i]);//if not included in the direct output of DIC } }
Simple use of generics and collections in C #