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; List<t> in a namespace
Using System.Collections; ArrayList in a namespace
Implements a collection of lists, a generic set, a non-generic
Here 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 the container size of the list is not set, the default is 0, as long as the element is added, it will automatically expand to 4, if the 5th element is added, it becomes 8, 9th join, 16
As can be seen, always multiply, expand to re-open the memory, this will affect efficiency, if you know the number of elements in advance, or the number of possible, it is best to give a big tradeoff value
We add 3 elements and 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 expansion
list<person> list = new list<person> (4);

List. Add (p1);
List. ADD (p2);
List. ADD (p3);

This method is to clear more than the unused memory space, example: if the opening size of 100, and we only use 4, the rest of the put, is not very wasteful
When this method is called, it checks whether the number of elements is more than 90% of the container size, and if so, does not recycle.
List. TrimExcess ();

The ArrayList method is the same as the list<> usage, and the difference is that it is a collection of objects, and the argument is an object that will have the possibility of packing and unpacking, as far as possible list<>
No more demonstrations in the department.


1 Initializing the Collector
C#3.0 started by providing initialization functionality, but did not react to IL code, in IL, as well as converting it into an Add method to invoke
list<int> L2 = new List<int> () {1, 2, 3, 4, 5};


2 adding elements AddRange () This method can add a batch of objects at once
list<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", +), new person ("Zhao", 6)});


3 inserting elements
Using the Insert () method, you can insert an element at a specified location
In the case of 1 position insertion, we finally became 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", 88));

foreach (person p in mylist)
{
Console.WriteLine (P.name);
}


4 Accessing elements
Both ArrayList and list<t> are provided with an indexer to access the
Console.WriteLine ("----------------Access Element------------------------");

for (int i = 0; i < MyList. Count; i++)
{
Console.WriteLine (Mylist[i].name);
}
You can also use a foreach drop-down device, where no example

Using the Foreach method
public delegate void action<t> (T obj), example with delegate as parameter
We'll use it, Mom. Day expression Implementation
Console.WriteLine ("-----------------output------------------------with the Foreach Method");

MyList. ForEach (param = Console.WriteLine (param.name));


5 Deleting an element
Delete element can pass in indexer value directly using RemoveAt ()
Remove the first element directly
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", 100);

Lists2. ADD (Per1);
Lists2. ADD (PER2);
Lists2. ADD (PER3);

Lists2. Remove (PER3);

Console.WriteLine ("-------deleted element---------");

foreach (person per in lists2)
{
Console.WriteLine (Per.name);
}
It can be seen from the results that the element named Jacky was deleted.
Let's talk about the remove procedure for the Remove method
Use the IndexOf method to determine the index of the object and then delete by index
Within the IndexOf method, the first check is whether the element implements the IEquatable interface, and if so, the Equals method in the interface is called.
If there is no implementation, call the Equals method in object to compare elements (that is, address comparison)
The above we removed Per3, very obviously an address, so was deleted

Below we modified the person, implemented the IEQUATABLE<PERSON>, in the comparison method, always return False, the PER3 will be compared to fail, will not be deleted
The results are all 3.
If you want to delete an object, it is best to delete it directly, because the Remove method undergoes a series of procedures before it is deleted by index!

RemoveRange () Delete a range
First parameter start position second number
Lists2. RemoveRange (1, 2);
Console.WriteLine ("----------------after bulk deletion");

foreach (person per in lists2)
//{
Console.WriteLine (Per.name);
//}


6 Search
There are many ways to search, you can use indexof LastIndexOf findindex findlasindex Find Findlas, you can use the exists () method if you just view the element save
The IndexOf () method requires an object to be parameterized, and if hit, returns the index of this element in the collection, and returns -1,indexof if it is not found. You 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", 100);

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
You can also specify a search range starting at 3rd, with a range length of 1
int index2 = LS3. IndexOf (person3,2,1);
Console.WriteLine (INDEX2);
IEquatable comparison method has been written before, no longer an example

The FindIndex () method is used to search for elements with certain characteristics
The example uses the delegate to make the parameter public delegate bool Predicate<t> (T obj);

int index3 = LS3. FindIndex (param = param.name.Equals ("Jacky"));
Console.WriteLine (index3);//2
FindLastIndex is the first element to be seen from the back, because we don't have duplicate elements here, so it doesn't show that he's only looking for one, and it stops.
int index4 = LS3. FindLastIndex (p = p.name.equals ("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
Person PPP = LS3. Find (P = = P.name.equals ("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 objects of all ages 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 (P.name);
}


7 sort
List can be sorted by the sort method, and the implementation algorithm is quick to sort
This method has several overloads

public void Sort (); This method can be used only if the element is IComparable, and if it is implemented, it may be called immediately after the sort is sorted.
public void Sort (comparison<t> Comparison); Our person does not implement that interface, so the method of using generic delegates as arguments
public void Sort (icomparer<t> comparer); Generic interface when the parameters public delegate int comparison<t> (t x, t y);
public void Sort (int index, int count, icomparer<t> comparer); You can specify a 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", 44);

Ls4. ADD (PERSON4);
Ls4. ADD (PERSON5);
Ls4. ADD (PERSON6);

Ls4. Sort (Mycomparfunc);
Console.WriteLine ("--------------------------after sorting");

foreach (person p in LS4)
{
Console.WriteLine (p.name+ p.age);
}

Console.WriteLine ("--------Upside down Sequential------------------");
Ls4. Reverse ();

foreach (person p in LS4)
{
Console.WriteLine (p.name+ p.age);
}


8 Type conversions
You can convert the elements in the collection to any type of element, for example, we want to convert the person in the collection to 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); Delegate parameters
list<racer> LS5 = ls4. convertall<racer> (Input) = new Racer (input.name));

Console.WriteLine ("-----------The converted thing--------");
foreach (Racer R in LS5)
{
Console.WriteLine (R.name);
}


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 modify it.
You can use a read-only collection, use the AsReadOnly method () to return the readonlycollection<t> type, which is the same as the list<> operation, but if you have an operation that modifies the collection, the exception is planed
He blocked the usual add methods.

Readonlycollection<racer> persss = ls5. AsReadOnly ();

Console.WriteLine ("Output read-only collection");

foreach (Racer R in Persss)
{
Console.WriteLine (R.name);
}

Console.ReadLine ();

}

Delegate implementation method for comparing writes
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;
}
}
}

Both helper classes
Class person//:iequatable<person>
{
public string name;
public int age;

Public person (string name, int age)
{
This.name= name;
This.age = age;
}

Always give a value of false
public bool Equals (person other)
//{
return false;
//}

}

Class Racer
{
public string name;

Public Racer (string name)
{
This.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: info-contact@alibabacloud.com 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.