Home >Backend Development >C#.Net Tutorial >Summary of the basic usage of C# generic list List

Summary of the basic usage of C# generic list List

高洛峰
高洛峰Original
2016-12-19 15:59:151588browse

The sample code is as follows:
namespace SampleListT
{
class Program
{
static void Main(string[] args)
{
//using System.Collections.Generic; List
//using System in the namespace .Collections; ArrayList in the namespace
//Both implement list collections, one is a generic collection and the other is non-generic
//Now 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 specified, the default is 0, as long as When an element is added, it will automatically expand to 4. When the fifth element is added, it becomes 8, and when the ninth element is added, it becomes 16
//It can be seen that it always grows exponentially, and it needs to be expanded when expanding. Reopening the memory will affect efficiency. If you know the number of elements in advance, or the possible number, it is best to give a trade-off value as large as possible
//We add 3 elements, and set the container size to 4. Note: Set to 4 It does not mean that only 4 elements can be placed. If it is exceeded, it will be expanded exponentially. This is just to maximize the overhead caused by expansion
List list = new List(4);

list.Add (p1);
list.Add(p2);
list.Add(p3);

//This method is to clear excess unused memory space. For example: if the allocation size is 100, and we only use 4. Isn’t it a waste to leave the rest? //When this method is called, it will check whether the number of elements accounts for more than 90% of the container size. If so, it will not be recycled.
list.TrimExcess();

//The ArrayList method is used the same as List<>, the difference is that it is a collection of objects, and the parameter is Object, so there is the possibility of boxing and unboxing. Try to use List<>

//No more demonstrations here

// 1 Initialization collector
// Starting from C# 3.0, the initialization function is provided, but it is not reflected in the IL code. In IL, it is also converted into ADD Method to call
List l2 = new List() { 1 ,2 ,3 ,4 ,5 };

// 2 Add elements AddRange() This method can add a batch of objects at one time
List lists = new List(10);
//The parameter is an object that must be updated, or it can be an array
list.AddRange( new Person[] { new Person( "aladdin" ,20) , new Person("zhao",6)});

//Construct the incoming batch parameters, which has the same effect as AddRange

List mylist = new List(new Person[] { new Person( " aladdin" ,20) , new Person("zhao",6)});

// 3 Insert elements
// Using the Insert() method, you can insert elements at the specified position
// For example, we insert at position 1 Then it finally became aladdin jacky zhao.. The insertion means that I occupy this position. The one who occupied this position before and the one after him will all be moved back one
mylist.Insert( 1 , new Person( "jacky" , 88 ));

foreach (Person p in mylist)

{
Console.WriteLine(p.name);
}

// 4 Access elements
// ArrayList and List both provide indexes
Console.WriteLine( "-------------Accessing elements---------------------- --");

for (int i = 0; i < mylist.Count; i++)

{
Console.WriteLine(mylist[i].name);
}
//You can also use the foreach drop generator To implement, no more examples here

//Use the Foreach method

//public delegate void Action(T obj); examples use delegates as parameters
//We use Day expressions to implement some places
Console.WriteLine( "-----------------Use the ForEach method to output-------------------------------- ");

mylist.ForEach( param => Console.WriteLine(param.name) ) ;

// 5 Delete elements
//To delete elements, you can use RemoveAt() to directly pass in the indexer value
// Delete the first element directly
mylist.RemoveAt(0);
//You can also pass the element to be deleted to the Remove method

List lists2 = new List(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( "-------Removed element---------" );

foreach (Person per in lists2)
{
Console.WriteLine(per.name);
}
//It can be seen from the result that the element named Jacky has been deleted
//Let’s talk about the deletion process of the Remove method
// Use the IndexOf method to determine the index of the object, and then delete it by index
// In the IndexOf method, first check whether the element implements the IEquatable interface. If so, call the Equals method in this interface
// If it is not implemented , then call the Equals method in Object to compare elements (that is, address comparison)
// Above we deleted per3, which is obviously an address, so it was deleted

// Next we modified Person and implemented IEquatable// The results are all 3
// If you want to delete the object, it is best to use the index to delete it directly, because the Remove method has gone through a After the series process, delete by index at the end!

//RemoveRange() deletes a range
//The second number of the starting position of the first parameter
//lists2.RemoveRange(1, 2);
//Console .WriteLine( "After batch 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. If you just want to check whether the element exists, you can use the Exists() method
// IndexOf( ) method requires an object as a parameter. If it is found, it returns the index of the element in the collection. If it cannot be found, it returns -1. IndexOf can also use the IEquatable interface to compare elements

List ls3 = new List(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 interface
int index = ls3. IndexOf(person3);
Console.WriteLine( "index of per3:" + index); //2
// You can also specify the search range to start from the 3rd one, and the range length is 1
int index2 = ls3.IndexOf(person3 ,2,1);
Console.WriteLine(index2);
//The IEquatable comparison method has been written before, no examples will be given

//The FindIndex() method is used to search for elements with certain characteristics
//Example Use delegates as parameters public delegate bool Predicate(T obj);

int index3 = ls3.FindIndex(param => param.name.Equals("jacky"));
Console.WriteLine( index3 );/ / 2
// FindLastIndex searches for the first element that appears from the back. Because we have no duplicate elements here, it does not reflect the effect of just finding one and then stopping.
int index4 = ls3.FindLastIndex(p => p.name.Equals("aladdin"));
Console.WriteLine(index4);
//The Find method is used the same as the FindIndex method, except that it returns the element itself
Person ppp = ls3.Find( p => p.name.Equals("jacky")) ;
Console.WriteLine(ppp);

// If you want to find all matching elements instead of stopping when you find the first one, use the FindAll method
// We find all objects whose age is equal to 100, and 3 of them match
List 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 using the Sort method. The implementation algorithm is quick sort
//This method has several overloads

//public void Sort(); //This method can only be used if IComparable is implemented for the element. If it is implemented Then, you can directly call sort once and the order will be sorted
//public void Sort(Comparison comparison); //Our Person does not implement that interface, so we need to use a generic delegate as a parameter.
//public void Sort(IComparer comparer); //Generic interface as parameter public delegate int Comparison(T x, T y);
//public void Sort(int index, int count, IComparer< ;T> comparer); //You can specify the range

List ls4 = new List(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( "-------------sorted-------------");

foreach (Person p in ls4)
{
Console.WriteLine(p.name+ p.age );
}

Console.WriteLine( "--------Reverse the order------------- ----");
ls4.Reverse();

foreach (Person p in ls4)
{
  Console.WriteLine(p.name+ p.age);
}


// 8 Type Conversion
//You can convert the elements in the collection into any type of elements. For example, we want to convert the Person in the collection into a Racer object. Racer only contains the name, no age
// public List(Converter converter);
// public delegate TOutput Converter(TInput input); Delegate parameters
List ls5 = ls4.ConvertAll((input ) => new Racer(input.name)) ;

Console.WriteLine( "-----------Converted stuff--------");
foreach (Racer r in ls5)
{
Console.WriteLine(r.name);
}


// 9 Read-only collection
// After the collection is created, it must be readable and writable. If not, it cannot New elements have been added, but if you think the filling is complete, do not make any modifications.
// You can use a read-only collection and use the AsReadOnly method () to return the ReadOnlyCollection type, which is the same as the List<> operation. But once there is an operation to modify the collection, an exception will occur
// It blocks the usual ADD and other methods

ReadOnlyCollection persss = ls5.AsReadOnly();

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

foreach (Racer r in persss)
{
Console.WriteLine(r.name);
}

Console.ReadLine();

}

//Delegation implementation method written for comparison
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;
}
                                                                                                                                                                                                                                 ;

public Person( string name , int age )

                                                                                                                                                  . {
           // return false;
                                                                           }
}
}





For more related articles about the basic usage summary of C# generic list List, please pay attention to the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn