How to use the C # list

Source: Internet
Author: User
Collections are an important concept in OOP, and the full support for collections in C # is one of the best of the language.

Why use a generic collection?

There are two main ways to implement a collection before C # 2.0:

A. Using ArrayList

It is intuitive to put objects directly into ArrayList, but because the items in the collection are of type object, a tedious type conversion is required for each use.

B. Using a custom collection class

A more common practice is to inherit a custom class from the CollectionBase abstract class and implement a strongly typed collection by encapsulating the IList object. This approach requires that a corresponding custom class be written for each collection type, with a large workload. The emergence of generic collections solves the above problem with a single line of code to create a collection of the specified type.

What is a generic type?

Generics are new in C # 2.0 (called templates in C + +) and are primarily used to solve a series of similar problems. This mechanism allows you to pass a class masterpiece as a parameter to a generic type and generate the corresponding object. It may be better to understand generics (including classes, interfaces, methods, delegates, etc.) as templates, and the variant parts of the template will be replaced with the class names passed in as parameters, resulting in a new type definition. Generics are a relatively large topic, where no detailed analysis, interested people can access the relevant information.



How do I create a generic collection?

The main use of the System.Collections.Generic namespace under the List<t> generic class to create a collection, the syntax is as follows:

Define the person class as follows:

As you can see, the generic collection greatly simplifies the implementation code of the collection, which makes it easy to create a collection of the specified types. Instead, generic collections provide more powerful functionality, and look at the sort and search below.

list<t> Listoft = new list<t> ();

The "T" is the type you want to use, either a simple type, such as a string, an 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

{

get {return _age;}

}

}

Create Person Object

person P1 = new Person ("Zhang San", 30);

person P2 = new Person ("John Doe", 20);

Person P3 = new Person ("Harry", 50);

To create a collection of objects of type person

list<person> persons = new list<person> ();

Putting a person object into a collection

Persons. Add (p1);

Persons. ADD (p2);

Persons. ADD (p3);

Output the name of a 2nd person

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

Ordering of generic collections

Sorting is based on comparison, to sort, first to compare. For example, there are two numbers 1, 2, to sort them, first of all to compare the two numbers, according to the comparison results to sort. If you are comparing objects, it is a bit more complicated, such as comparing a person object, either by name or by age, which requires a comparison rule to be determined. An object can have multiple comparison rules, but there can be only one default rule, and the default rule is placed in the class that defines the object. The default comparison rule is defined in the CompareTo method, which belongs to the icomparable<t> generic interface. Take a look at the following code:

Class person:icomparable<person>

{

Compare by age

public int CompareTo (person p)

{

return this. Age-p.age;

}

}

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

Once you have defined the default comparison rules, you can sort the collection by using the Sort method without parameters, as follows:

To sort a collection by default rules

Persons. Sort ();

Output owner Name

foreach (person p in persons)

{

Console.WriteLine (P.name); Output order is "John Doe", "Zhang San", "Harry"

}

In practice, it is often necessary to sort the set according to a number of different rules, which requires defining additional comparison rules, which can be defined in the Compare method, which belongs to the icomparer<t> generic interface, see the following code:

Class namecomparer:icomparer<person>

{

Storing the Sequencer instance

public static Namecomparer Default = new Namecomparer ();

Compare by name

public int Compare (person P1, person p2)

{

Return System.Collections.Comparer.Default.Compare (P1. Name, p2. Name);

}

}

The parameters of the Compare method are the two homogeneous objects to be compared, the return value is type int, and the return value processing rule is the same as the CompareTo method. The Comparer.default returns a built-in comparer object that compares two objects of the same type.

The collection is sorted using the newly defined comparer:

A delegate can also be used to sort the collection, first to define a method for the delegate to call, to hold the comparison rules, you can use static methods. Take a look at the following code: Then sort the collection by using the built-in generic delegate system.comparison<t>:

As you can see, the last two ways to sort the collection according to the specified rules, but the author is more inclined to use the delegate method, you can consider the various comparison rules in a class, and then make flexible calls.

Sort the collection by name

Persons. Sort (Namecomparer.default);

Output owner Name

foreach (person p in persons)

{

Console.WriteLine (P.name); Output order is "John Doe", "Harry", "Zhang San"

}class Personcomparison

{

Compare by name

public static int Name (person P1, person p2)

{

Return System.Collections.Comparer.Default.Compare (P1. Name, p2. Name);

}

}

The parameters of the method are the two homogeneous objects to be compared, the return value is type int, and the return value processing rule is the same as the CompareTo method.

system.comparison<person> Namecomparison = new system.comparison<person> (PersonComparison.Name);

Persons. Sort (Namecomparison);

Output owner Name

foreach (person p in persons)

{

Console.WriteLine (P.name); Output order is "John Doe", "Harry", "Zhang San"

}

As you can see, the last two ways to sort the collection according to the specified rules, but the author is more inclined to use the delegate method, you can consider the various comparison rules in a class, and then make flexible calls.

Search for generic collections

Search is to find items that meet specific criteria from the collection, you can define multiple search criteria, and make calls as needed. First, define the search criteria as follows:

Class Personpredicate

{

Find middle-aged (over 40 yrs)

public static bool Midage (person P)

{

if (P.age >= 40)

return true;

Else

return false;

}

}

The above search conditions are placed in a static method, the return type of the method is Boolean, the item in the collection that satisfies a particular condition returns true, otherwise false is returned.

system.predicate<person> midagepredicate = new system.predicate<person> (PERSONPREDICATE.MIDAGE);

list<person> midagepersons = persons. FindAll (midagepredicate);

Output all middle-aged names

foreach (person p in midagepersons)

{

Console.WriteLine (P.name); Output "Harry"

The collection is then searched through the built-in generic delegate system.predicate<t>:

Extension of a generic collection

What if you want to get the names of everyone in the collection, separated by commas?

Given the limited functionality that a single class can provide, it is natural to think of extending the List<t> class, which is also a class, and therefore can be extended by inheritance. Take a look at the following code:

Defining Persons collection classes

Class persons:list<person>

{

Get the names of all the people in the collection

public string Getallnames ()

{

if (this. Count = = 0)

Return "";

String val = "";

foreach (person p in this)

{

Val + = P.name + ",";

}

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 owner Name

Console.Write (Personcol.getallnames ()); Output "Zhang San, John Doe, Harry"

List method and property method or Property function

The capacity is used to get or set the number of elements the list can hold. This value is automatically increased when the quantity exceeds the capacity. You can set this value to reduce capacity, or you can call the Trin () method to reduce capacity to fit the actual number of elements.

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

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

Add () A public method that adds an object to the list

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

BinarySearch () Overloads the public method used to locate the specified element using a binary lookup within the sorted list.

Clear () Removes all elements from the list

Contains () tests whether an element is inside a list

CopyTo () overloaded public method that copies a list into a one-dimensional array

Exists () tests whether an element is inside a list

Find () finds and returns the first occurrence of a matching element within a list

FindAll () finds and returns all matching elements within the list

GetEnumerator () overloaded public method, returns an enumerator for iterating the list

Getrange () copies the specified range of elements into the new list

IndexOf () overloaded public method that finds and returns the index of each matching element

Insert () Inserts an element inside the list

Insertrange () Inserts a set of elements within a list

LastIndexOf () Overloads the 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 from the specified index

RemoveRange () removes elements from a specified range

Reverse () Reverses the order of elements within a list

Sort () sorts the elements within a list

ToArray () copies the elements within the list into a new array

TrimToSize () Sets the capacity to the actual number of elements in the list

Summary:

This article focuses on the use of generics in C # 2.0 to implement the collection, as well as the expansion of the collection function, the appropriate use of generic collection, can reduce a lot of duplication of work, greatly improve development efficiency. In fact, a collection is just a typical application of generics, and if you want to learn more about generics, you can look at other relevant information. I hope this article will be useful to you



Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.