Home >Backend Development >C#.Net Tutorial >Summary of the basic usage of C# generic list List
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.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();
//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
// 2 Add elements AddRange() This method can add a batch of objects at one time
List
//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)});
List
// 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 ));
{
Console.WriteLine(p.name);
}
// 4 Access elements
// ArrayList and List
Console.WriteLine( "-------------Accessing elements---------------------- --");
{
Console.WriteLine(mylist[i].name);
}
//You can also use the foreach drop generator To implement, no more examples here
//public delegate void Action
//We use Day expressions to implement some places
Console.WriteLine( "-----------------Use the ForEach method to output-------------------------------- ");
// 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
Person per2 = new Person("zhao", 100);
Person per3 = new Person("jacky", 100);
lists2. Add(per2);
lists2.Add(per3);
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
// 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
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
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
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
//public void Sort(IComparer
//public void Sort(int index, int count, IComparer< ;T> comparer); //You can specify the range
List
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
// public delegate TOutput Converter
List
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
// It blocks the usual ADD and other methods
ReadOnlyCollection
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;
}
;
. {
// return false;
}
}
}
For more related articles about the basic usage summary of C# generic list List