How to use C# list

Dec 15, 2016 pm 03:26 PM

Collection is an important concept in OOP, and the comprehensive support for collections in C# is one of the essence of the language.

Why use generic collections?

Before C# 2.0, collections could be implemented in two main ways:

a. Use ArrayList

to directly put objects into ArrayList. The operation is intuitive, but because the items in the collection are of type Object, they must be used every time Perform cumbersome type conversions.

b. Use a custom collection class

A common approach is to inherit a custom class from the CollectionBase abstract class and implement a strongly typed collection by encapsulating the IList object. This method requires writing a corresponding custom class for each collection type, which requires a large workload. The emergence of generic collections has better solved the above problems. It only takes one line of code to create a collection of a specified type.

What are generics?

Generics are a new element in C# 2.0 (called templates in C++), which are mainly used to solve a series of similar problems. This mechanism allows passing a class name as a parameter to a generic type and producing the corresponding object. It may be better to think of generics (including classes, interfaces, methods, delegates, etc.) as templates. The variant part in the template will be replaced by the class name passed in as a parameter, thereby obtaining a new type definition. Generics is a relatively large topic and will not be analyzed in detail here. Those who are interested can consult relevant information.



How to create a generic collection?

Mainly use the List generic class under the System.Collections.Generic namespace to create a collection. The syntax is as follows:

Define the Person class as follows:

It can be seen that the generic collection greatly simplifies the implementation code of the collection. With it, you can easily create collections of specified types. Not only that, generic collections also provide more powerful functions. Let’s take a look at sorting and searching.

List ListOfT = new List();

The "T" is the type to be used, which can be a simple type, such as string, int, or a user-defined type. Let’s look at a specific example.


class Person

{

​ private string _name; //Name

​ private int _age; //Age

​ //Create Person object

​​ public Person(string Name, int Age)

​​

this._name= Name;

this._age = Age;

}

//Name

public string Name

{

get { return _name; }

}

//Age

public int Age

{g Get {Return_age;}}}} // Create Person Objects

Person P1 = New Person ("Zhang San", 30);

Person P2 = New Person ( "李思", 20);

Person p3 = new Person("王五", 50);

//Create a collection of objects of type Person

List persons = new List() ;

//Put the Person object into the collection

persons.Add(p1);

persons.Add(p2);

persons.Add(p3);

//Output the name of the second person

Console.Write(persons[1].Name);

Sorting of generic collections

Sorting is based on comparison. To sort, you must first compare. For example, there are two numbers 1 and 2. To sort them, you must first compare the two numbers and sort them according to the comparison results. If you want to compare objects, the situation is a little more complicated. For example, when comparing Person objects, you can compare by name or by age, which requires determining the comparison rules. An object can have multiple comparison rules, but there can only be one default rule, which is placed in the class that defines the object. The default comparison rules are defined in the CompareTo method, which belongs to the IComparable generic interface. Please see the following code: lClass Person: iComparable & LT; Person & GT; }

}

The parameter of the CompareTo method is another object of the same type to be compared with, and the return value is int type. If the return value is greater than 0, it means that the first object is greater than the second object. If the return value is less than 0 means that the first object is smaller than the second object. If 0 is returned, the two objects are equal.

After defining the default comparison rules, you can sort the collection through the Sort method without parameters, as shown below:

// Sort the collection according to the default rules

persons.Sort();

//Output the names of all persons

foreach (Person p in persons)

{

Console.WriteLine(p.Name); //The output order is "李思", "张三", "王五"

}

In actual use, collections often need to be sorted according to many different rules. This requires defining other comparison rules, which can be defined in the Compare method. This method belongs to the IComparer generic interface. Please see below. Code:

class NameComparer: IComparer

{

//Storage sorter instance

public static NameComparer Default = new NameComparer();

//Compare by name

public int Compare(Person p1, Person p2)

                                                                                                                                   Comparer.                                                                    return System.Collections.Comparer.Default.Compare(p1.Name, p2.Name); , the return value is int type, and the return value processing rules are the same as the CompareTo method. Comparer.Default among them returns a built-in Comparer object for comparing two objects of the same type.

Next, use the newly defined comparator to sort the collection:

You can also sort the collection through delegation. First, you need to define a method for the delegation to call to store comparison rules. You can use a static method. Please look at the code below: Then sort the collection through the built-in generic delegate System.Comparison:

As you can see, the latter two methods can sort the collection according to the specified rules, but the author prefers to use In the delegation method, you can consider putting various comparison rules in a class and then calling them flexibly.

//Sort the collection by name

persons.Sort(NameComparer.Default);

//Output everyone’s name

foreach (Person p in persons)

{

Console.WriteLine(p.Name ;

 {

                                                                                                                                                                                                                                                  return System.Collections.Comparer.Default.Compare(p1.Name, p2.Name); Type, return value processing rules are the same as the CompareTo method.

System.Comparison NameComparison = new System.Comparison(PersonComparison.Name);

persons.Sort(NameComparison);

//Output everyone’s name

foreach (Person p in persons)

{

Console.WriteLine(p.Name); //The output order is "Li Si", "Wang Wu", "Zhang San"

}

As you can see, the latter two methods can be used to set the collection according to Specify rules for sorting, but the author prefers to use delegation. You can consider putting various comparison rules in a class and then call them flexibly.

Search for generic collections

Search is to find items that meet specific conditions from the collection. Multiple search conditions can be defined and called as needed. First, define the search conditions as follows:

class PersonPredicate

{

​ // Find middle-aged people (over 40 years old)

​ public static bool MidAge(Person p)

​ {

​​ if (p. Age > satisfy specific The condition's item returns true, otherwise it returns false.

System.Predicate MidAgePredicate = new System.Predicate(PersonPredicate.MidAge);

List MidAgePersons = persons.FindAll(MidAgePredicate);

//Output the names of all middle-aged people

foreach (Person p in MidAgePersons)

{

Console.WriteLine(p.Name); //Output "王五"

} Then search the collection through the built-in generic delegate System.Predicate:

Extension of generic collection

If you want to get the names of all the people in the collection, separated by commas, what should you do?

Considering that the functions that a single class can provide are limited, it is natural to think of extending the List class. Generic classes are also classes, so they can be extended through inheritance. Please look at the code below:

//Define the Persons collection class

class Persons: List

{

​ //Get the names of all people in the collection

​​ public string GetAllNames()

​​ {

​​​​​ this.Count == 0)

                                                                   ;

}

           return val.Substring(0, val.Length - 1);

     }

}

//Create and populate the Persons collection

Persons PersonCol = new Persons();

PersonCol.Add(p1);

PersonCol.Add(p2);

PersonCol.Add(p3);

//Output everyone’s name

Console.Write(PersonCol.GetAllNames()); //Output "Zhang San, Li Si, Wang Wu ”

Methods and attributes of List Method or attribute function

Capacity is used to get or set the number of elements that the List can accommodate. This value will automatically grow when the quantity exceeds the capacity. You can set this value to reduce the capacity, or call the trin() method to reduce the capacity to fit the actual number of elements.

Count property, used to get the current number of elements in the array

Item() Gets or sets the element by specifying the index. For the List class, it is an indexer.

Add( ) Public method for adding an object to the List

AddRange( ) Public method, adding multiple elements that implement the ICollection interface at the end of the List

BinarySearch( ) Overloaded public method, used for sorting Binary search is used to locate the specified element in the List.

Clear( ) Removes all elements in the List

Contains( ) Tests whether an element is in the List

CopyTo( ) Overloaded public method, copies a List to In a one-dimensional array

Exists() tests whether an element is in the List

Find() finds and returns the first matching element that appears in the List

FindAll() finds and returns all matching elements in the List

GetEnumerator() Overloaded public method, returns an enumerator for iterating List

Getrange() Copies the elements in the specified range to a new List

IndexOf() Overloaded public method, finds and returns each The index of the matching element

Insert() Insert an element in the List

InsertRange() Insert a set of elements in the List

LastIndexOf() Overloaded public method, finds and returns the index of the last matching element

Remove( ) removes the first element that matches the specified element

RemoveAt( ) removes the element at the specified index

RemoveRange( ) removes the elements in the specified range

Reverse( ) reverses the order of the elements in the List

Sort() Sorts the elements in the List

ToArray() Copies the elements in the List to a new array

trimToSize() Sets the capacity to the actual number of elements in the List

Summary:

This article focuses on Yu introduces the use of generics in C# 2.0 to implement collections and expand collection functions. Appropriate use of generic collections can reduce a lot of repetitive work and greatly improve development efficiency. In fact, collections are just a typical application of generics. If you want to know more about generics, you can check other related information. I hope this article is useful to you

For more articles related to how to use C# 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 Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

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)

Hot Topics

Java Tutorial
1677
14
PHP Tutorial
1279
29
C# Tutorial
1257
24
The Continued Relevance of C# .NET: A Look at Current Usage The Continued Relevance of C# .NET: A Look at Current Usage Apr 16, 2025 am 12:07 AM

C#.NET is still important because it provides powerful tools and libraries that support multiple application development. 1) C# combines .NET framework to make development efficient and convenient. 2) C#'s type safety and garbage collection mechanism enhance its advantages. 3) .NET provides a cross-platform running environment and rich APIs, improving development flexibility.

Deploying C# .NET Applications to Azure/AWS: A Step-by-Step Guide Deploying C# .NET Applications to Azure/AWS: A Step-by-Step Guide Apr 23, 2025 am 12:06 AM

How to deploy a C# .NET app to Azure or AWS? The answer is to use AzureAppService and AWSElasticBeanstalk. 1. On Azure, automate deployment using AzureAppService and AzurePipelines. 2. On AWS, use Amazon ElasticBeanstalk and AWSLambda to implement deployment and serverless compute.

C# as a Versatile .NET Language: Applications and Examples C# as a Versatile .NET Language: Applications and Examples Apr 26, 2025 am 12:26 AM

C# is widely used in enterprise-level applications, game development, mobile applications and web development. 1) In enterprise-level applications, C# is often used for ASP.NETCore to develop WebAPI. 2) In game development, C# is combined with the Unity engine to realize role control and other functions. 3) C# supports polymorphism and asynchronous programming to improve code flexibility and application performance.

C# and the .NET Runtime: How They Work Together C# and the .NET Runtime: How They Work Together Apr 19, 2025 am 12:04 AM

C# and .NET runtime work closely together to empower developers to efficient, powerful and cross-platform development capabilities. 1) C# is a type-safe and object-oriented programming language designed to integrate seamlessly with the .NET framework. 2) The .NET runtime manages the execution of C# code, provides garbage collection, type safety and other services, and ensures efficient and cross-platform operation.

C# .NET: Building Applications with the .NET Ecosystem C# .NET: Building Applications with the .NET Ecosystem Apr 27, 2025 am 12:12 AM

How to build applications using .NET? Building applications using .NET can be achieved through the following steps: 1) Understand the basics of .NET, including C# language and cross-platform development support; 2) Learn core concepts such as components and working principles of the .NET ecosystem; 3) Master basic and advanced usage, from simple console applications to complex WebAPIs and database operations; 4) Be familiar with common errors and debugging techniques, such as configuration and database connection issues; 5) Application performance optimization and best practices, such as asynchronous programming and caching.

.NET Framework vs. C#: Decoding the Terminology .NET Framework vs. C#: Decoding the Terminology Apr 21, 2025 am 12:05 AM

.NETFramework is a software framework, and C# is a programming language. 1..NETFramework provides libraries and services, supporting desktop, web and mobile application development. 2.C# is designed for .NETFramework and supports modern programming functions. 3..NETFramework manages code execution through CLR, and the C# code is compiled into IL and runs by CLR. 4. Use .NETFramework to quickly develop applications, and C# provides advanced functions such as LINQ. 5. Common errors include type conversion and asynchronous programming deadlocks. VisualStudio tools are required for debugging.

C# .NET Development: A Beginner's Guide to Getting Started C# .NET Development: A Beginner's Guide to Getting Started Apr 18, 2025 am 12:17 AM

To start C#.NET development, you need to: 1. Understand the basic knowledge of C# and the core concepts of the .NET framework; 2. Master the basic concepts of variables, data types, control structures, functions and classes; 3. Learn advanced features of C#, such as LINQ and asynchronous programming; 4. Be familiar with debugging techniques and performance optimization methods for common errors. With these steps, you can gradually penetrate the world of C#.NET and write efficient applications.

C# and .NET: Understanding the Relationship Between the Two C# and .NET: Understanding the Relationship Between the Two Apr 17, 2025 am 12:07 AM

The relationship between C# and .NET is inseparable, but they are not the same thing. C# is a programming language, while .NET is a development platform. C# is used to write code, compile into .NET's intermediate language (IL), and executed by the .NET runtime (CLR).

See all articles