Summary of basic usage of C # generic list list<t>

Source: Internet
Author: User
The sample code is as follows:

Namespace samplelistt{class Program {static void Main (string[] args) {//using System.Collections.Generic; naming The list<t>//using system.collections in space; The ArrayList//in the namespace implements a collection of lists, a generic set, a non-generic//under which we add the person object to the collection person P1 = new Person ("Aladdin", 20); person P2 = new Person ("Zhao", 10); Person P3 = new Person ("Jacky", 40);//If you do not make a list of container size, the default is 0, as long as there are elements to join IS, will automatically expand to 4, if the 5th element is added, it becomes 8, 9th join, as 16//can see, Always multiply, expand to re-open the memory, this will affect the efficiency, if you know the number of elements, or the number of possible, it is best to give a big tradeoff value//We add 3 elements, Set the container size to 4. Note: Set to 4 does not mean that only 4 elements can be placed, if exceeded, the same will be multiplied, just to maximize the cost of the extension list<person> list = new list<person> (4); Add (p1); list. ADD (p2); list. ADD (p3);//This method is to clear more than the unused memory space, such as: if the opening size of 100, and we only use 4, the rest of the put, is not very wasteful//This method call will check the number of elements is not accounted for the container size of more than 90%, if it is, do not recycle. List. TrimExcess (); The//arraylist method is the same as the list<> usage, the difference is that it is a collection of objects, the argument is an object that will have the possibility of packing and unpacking, as far as possible to use list<>//the place no longer do demo//1 initialization of the collector C#3.0 started, provided the initialization function, but did not react to the IL code, in IL, the same is converted into an Add method to call list<int> L2 = new List<int> () {1, 2, 3, 4, 5};//2 add Element AddRange () This method can add a batch of objects at once LIST&LT person> lists = new list<person> (10);//parameter is an object that must be possible to fall, but also an array List. AddRange (new person[] {new Person ("Aladdin", "a"), new person ("Zhao", 6)}); Constructs incoming batch parameters, as with the AddRange effect list<person> mylist = new list<person> (new person[] {new Person ("Aladdin"), NE W person ("Zhao", 6)});//3 Insert element//Use the Insert () method, you can insert the element//example at the specified position at the end of the 1 position insert is the Aladdin Jacky Zhao. Insert meaning, this bit I took up, before the former and he, and then moved back to a mylist. Insert (1, New person ("Jacky", "N"); foreach (person p in MyList) {Console.WriteLine (;} 4 Access elements//ArrayList and List<t> are Console.WriteLine ("----------------Access Element------------------------") that provide an indexer to access; for (int i = 0; i < MyList. Count; i++) {Console.WriteLine (mylist[i].name);} It can also be implemented using a foreach drop-down, where no example is used//using the Foreach method//public delegate void action<t> (T obj); Some places we use the Mother day expression to implement Console.WriteLine ("-----------------output------------------------with the Foreach Method"); MyList. ForEach (param = Console.WriteLine (;//5 Delete element//delete element you can pass in the indexer value directly using RemoveAt ()//Remove the first element directly from the mylist. RemoveAt (0);//You can also pass the element you want to delete to the Remove method list<person> lists2 = new list<person> (10); Person per1 = new Person ("Aladdin", 100); Person per2 = new Person ("Zhao", 100); Person Per3 = new Person ("Jacky", "lists2"); ADD (per1); lists2. ADD (PER2); lists2. ADD (Per3); lists2. Remove (PER3); Console.WriteLine ("-------deleted element---------"), foreach (person per in lists2) {Console.WriteLine (;} It can be seen from the result that the element with the name Jacky is deleted//the following is the removal process of the Remove method//using the IndexOf method to determine the index of the object, and then by index Delete//within the IndexOf method, first check whether the element implements the IEquatable interface , if yes, call the Equals method in this interface//if there is no implementation, then call the Equals method in object to compare elements (that is, address comparison)//above we delete per3, very obvious an address, so was deleted//below we modified the person, Implemented Iequatable<person> In the comparison method, always return false, then Per3 will fail, will not be deleted//results of 3 are in//if you want to delete an object, it is best to use the index to delete directly, because the Remove method after a series of procedures, Finally, delete!//by index RemoveRange () deletes a range//first parameter start position the second number of//lists2. RemoveRange (1, 2);//console.writeline ("----------------after bulk deletion")//foreach (person per in lists2)//{//Console.writel INE (;//}//6 search/Search There are many ways to use indexof LastIndexOf findindexFindlasindex Find Findlas, you can use the exists () method if you just view the element, or the IndexOf () method needs to make an object argument, and if hit, returns the index of this element in the collection, and returns 1 if it is not found. IndexOf can also use the IEquatable interface to compare elements list<person> LS3 = new list<person> (10); Person Person1 = new Person ("Aladdin", 100); Person Person2 = new Person ("Zhao", 100); Person Person3 = new Person ("Jacky", "LS3"); ADD (Person1); LS3. ADD (Person2); LS3. Add (Person3);//In order to use the default address comparison, we temporarily remove the person's interface int index = LS3. IndexOf (Person3); Console.WriteLine ("Per3 Index:" + index); 2//can also specify that the search range starts at 3rd, with a range length of 1int index2 = LS3. IndexOf (person3,2,1); Console.WriteLine (INDEX2);//iequatable comparison method has been written before, no longer an example//FindIndex () method is used to search for an element with a certain characteristics//example with a delegate to do the parameters public delegate bool predicate<t> (T obj); int index3 = LS3. FindIndex (param = ("Jacky")); Console.WriteLine (INDEX3),///2//FindLastIndex is from the back of the first occurrence of the element, because we do not have duplicate elements here, so it does not show that he only find one, the effect of stopping int index4 = LS3. FindLastIndex (p = ("Aladdin")); Console.WriteLine (index4);//The Find method is the same as the FindIndex method usage, and the difference is that it returns the element itself, the person PPP = LS3. Find (P = = ("Jacky")); Console.WriteLine (PPP);//If you want to find all the matching elements, instead of finding the first one to stop, use the FindAll method//We look for all objects of age equal to 100, and 3 match list<person> NewList = LS3. FindAll (p = p.age = = 100); Console.WriteLine ("----------Find All---------"), foreach (Person p in NewList) {Console.WriteLine (;} 7 Sort//list can be sorted by the sort method, the implementation algorithm is fast sort//This method has several overloads//public void Sort (); Only the elements implemented IComparable to use this method, if implemented, you can call the sort immediately after the order of//public void sort (comparison<t> Comparison); Our person does not implement that interface, so the method//public void Sort (icomparer<t> comparer) is used as the parameter of the generic delegate; Generic interface when the parameters public delegate int comparison<t> (t x, t y);//public void Sort (int index, int count, Icomparer<t> Co Mparer); You can specify the range list<person> LS4 = new list<person> (10); Person person4 = new Person ("Aladdin", 100); Person person5 = new Person ("Zhao", 33); Person person6 = new Person ("Jacky", "LS4"); ADD (person4); ls4. ADD (PERSON5); ls4. ADD (PERSON6); ls4. Sort (Mycomparfunc); Console.WriteLine ("--------------------------after sorting"); forEach (person p in Ls4) {Console.WriteLine ( p.age);} Console.WriteLine ("--------Upside Down------------------"); Ls4. Reverse (); foreach (person p in Ls4) {Console.WriteLine ( p.age);} 8 type conversion//can convert elements in a collection to any type of element, for example, we want to convert the person in the collection into a racer object racer contains only the name, no age/public list<toutput> ConvertAll <TOutput> (converter<t, toutput> Converter);//public Delegate TOutput Converter<tinput, toutput> (  Tinput input); The delegate parameter list<racer> LS5 = Ls4. convertall<racer> (Input) = new Racer (; Console.WriteLine ("-----------converted Thing--------"), foreach (Racer r in Ls5) {Console.WriteLine (;} 9 read-only collection//After the collection is created, it must be read-write, and if not, he can no longer add new elements, but if the fill is considered complete, do not make any changes.//You can use the read-only collection and use the AsReadOnly method () to return ReadOnlyCollection The <T> type, which is the same as the list<> operation, but a change of the set of operations, will be planed out of the exception//he blocked the usual Add method readonlycollection<racer> persss = ls5. AsReadOnly (); Console.WriteLine ("Output read-only collection"), foreach (Racer r in Persss) {Console.WriteLine (;}      Console.ReadLine (); }//in order to compare the writtenDelegate implementation method public static int Mycomparfunc (person P1, person p2) {if (p1.age = = p2.age) {return 0;} else if (P1.age > P2.age) {return 1;}      else{return-1;}      }}//two Helper Classes class Person//:iequatable<person> {public string name;      public int age;      Public person (string name, int.) { name;this.age = age;      }////always gives a false value//public bool Equals (person another)//{//return false;      }} class Racer {public string name;      Public Racer (string name) { name; }  }}

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.