search

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
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
Unity game development: C# implements 3D physics engine and AI behavior treeUnity game development: C# implements 3D physics engine and AI behavior treeMay 16, 2025 pm 02:09 PM

In Unity, 3D physics engines and AI behavior trees can be implemented through C#. 1. Use the Rigidbody component and AddForce method to create a scrolling ball. 2. Through behavior tree nodes such as Patrol and ChasePlayer, AI characters can be designed to patrol and chase players.

What does u mean in c language? Unsigned modification of u in c languageWhat does u mean in c language? Unsigned modification of u in c languageMay 16, 2025 pm 02:06 PM

u is used in C language to declare unsigned integer constants. 1. The u suffix represents an unsigned integer, such as 10u. 2. The range of unsigned integers starts from 0 and does not contain negative numbers. They are suitable for large-range positive numbers and bit operations. 3. Pay attention to overflow and negative number processing issues when using unsigned integers.

What does /0 mean in C language? Empty character /0 ending in stringWhat does /0 mean in C language? Empty character /0 ending in stringMay 16, 2025 pm 02:03 PM

In C language, /0 refers to an empty character, which is used to mark the end of a string. 1) The value of the null character in the ASCII code table is 0. 2) It is the basis for C string processing, and the compiler will automatically add null characters at the end of the string. 3) The empty character is not visible but exists in memory, telling the string function to end the string. 4) When using it, make sure that the string ends with empty characters to avoid undefined behavior.

What does bool represent in c language? What is the true and false value of bool type in c language?What does bool represent in c language? What is the true and false value of bool type in c language?May 16, 2025 pm 02:00 PM

In C language, the bool type is introduced through header files to represent true and false values. 1. The value of type bool can be true (1) or false (0), and any non-zero value is considered true. 2. Using bool types can improve the readability of the code, especially when dealing with complex logical conditions. 3. Although bool types are convenient, in some cases, using integer types for boolean operations may be more efficient.

How to calculate exponential function in C language to the x power of e in C languageHow to calculate exponential function in C language to the x power of e in C languageMay 16, 2025 pm 01:57 PM

In C language, you can use the Taylor series method and the exp function in the standard library to calculate the x power of e. 1. The Taylor series method is calculated through approximately, which is suitable for situations where the accuracy requirements are not high, but may overflow when large numbers are large. 2. The exp function method uses the math.h header file, with high accuracy and good optimization, but requires linking to the math library. The selection method needs to be based on specific needs.

What does avg mean in c language abbreviation of avg mean in c languageWhat does avg mean in c language abbreviation of avg mean in c languageMay 16, 2025 pm 01:54 PM

In C language, avg usually means "average", which is a common variable name for calculating the average value of a set of numbers. 1. Declare variables: use avg to store the average value. 2. Accumulation and calculation: traverse the dataset and accumulate all values, and then divide by the dataset length. 3. Result storage: Save the average value into the avg variable. Use double or float types to improve calculation accuracy.

What does aa mean in c language aa variable naming rules in c languageWhat does aa mean in c language aa variable naming rules in c languageMay 16, 2025 pm 01:51 PM

"aa" has no special meaning in C language, it is just a normal identifier. 1. Variable name rules: Only include letters, numbers and underscores, starting with letters or underscores, not keywords, and are case-sensitive. 2. Best practice: Use meaningful names, avoid being too long, use camels or underscore nomenclature to avoid confusing names.

What does f mean in C language? Detailed explanation of the meaning and common usage of f in C languageWhat does f mean in C language? Detailed explanation of the meaning and common usage of f in C languageMay 16, 2025 pm 01:48 PM

In C language, f represents floating point numbers, and the specific usage includes: 1. As a format specifier, used for printf and scanf functions; 2. Appear in mathematical function names, such as sinf and cosf; 3. As a floating point suffix, specify the type float; 4. Pay attention to accuracy issues in floating point operations and use tolerance for comparison; 5. Use float to optimize performance, but trade-offs are required.

See all articles

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

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.