How to use C# list

高洛峰
Release: 2016-12-15 15:26:29
Original
1522 people have browsed it

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!

Related labels:
source:php.cn
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template