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

Dec 19, 2016 pm 03:59 PM
Generics

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 of this Website
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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Do generic functions solve the problem of variadic parameter types in Golang? Do generic functions solve the problem of variadic parameter types in Golang? Apr 16, 2024 pm 06:12 PM

Generic functions in Go solve the problem of variadic types: generic functions allow type parameters to be specified at runtime. This makes it possible to write functions that can handle parameters of different types. For example, the Max function is a generic function that accepts two comparable parameters and returns the larger value. By using generic functions, we can write more flexible and general code that can handle different types of parameters.

Specific application scenarios of generics in golang Specific application scenarios of generics in golang May 04, 2024 am 11:45 AM

Application scenarios of generics in Go: Collection operations: Create collection operations suitable for any type, such as filtering. Data Structures: Write general-purpose data structures such as queues, stacks, and maps to store and manipulate various types of data. Algorithms: Write general-purpose algorithms such as sorting, search, and reduction that can handle different types of data.

What are the upper and lower bounds of Java function generics? how to use? What are the upper and lower bounds of Java function generics? how to use? Apr 26, 2024 am 11:45 AM

Java function generics allow setting upper and lower bounds. Extends specifies that the data type accepted or returned by a function must be a subtype of the specified type, e.g. The lower bound (super) specifies that the data type accepted or returned by a function must be a supertype of the specified type, e.g. The use of generics improves code reusability and security.

Explore the advantages and uses of generics in Golang Explore the advantages and uses of generics in Golang Apr 03, 2024 pm 02:03 PM

Answer: Golang generics are a powerful tool for improving code reusability, flexibility, type safety, and scalability. Detailed description: Advantages: Code reusability: Common algorithms and data structures Flexibility: Runtime creation of instances of specific types Type safety: Compile time type checking Extensibility: Easy to extend and customize Purpose: Common functions: sorting, comparison Common data structures such as lists, maps, stacks, etc. Type aliases: simplify type declarations Constrained generics: ensure type safety

What is the impact of Golang generics on function signatures and parameters? What is the impact of Golang generics on function signatures and parameters? Apr 17, 2024 am 08:39 AM

The impact of generics on Go function signatures and parameters includes: Type parameters: Function signatures can contain type parameters, specifying the types that the function can use. Type constraints: Type parameters can have constraints that specify conditions that they must satisfy. Parameter type inference: The compiler can infer the type of unspecified type parameters. Specifying types: Parameter types can be explicitly specified to call generic functions. This increases code reusability and flexibility, allowing you to write functions and types that can be used with multiple types.

Application of Java generics in Android development Application of Java generics in Android development Apr 12, 2024 pm 01:54 PM

The application of generics in Android development enhances code reusability, security and flexibility. The syntax consists of declaring a type variable T that can be used to manipulate type-parameterized data. Generics in action include custom data adapters, allowing the adapter to adapt to any type of custom data object. Android also provides generic list classes (such as ArrayList) and generic methods that allow the manipulation of parameters of different types. The benefits of using generics include code reusability, security, and flexibility, but care needs to be taken to specify the correct bounds and use them in moderation to ensure code readability.

What are the limitations of generic functions in Golang? What are the limitations of generic functions in Golang? Apr 16, 2024 pm 05:12 PM

Limitations of Go generic functions: only type parameters are supported, value parameters are not supported. Function recursion is not supported. Type parameters cannot be specified explicitly, they are inferred by the compiler.

How do Java enum types work with generics? How do Java enum types work with generics? May 04, 2024 am 08:36 AM

The combination of enumeration types and generics in Java: When declaring an enumeration with generics, you need to add angle brackets, and T is the type parameter. When creating a generic class, you also need to add angle brackets, T is a type parameter that can store any type. This combination improves code flexibility, type safety, and simplifies code.

See all articles