List generic set in C # -- Summary

Source: Internet
Author: User

Collections are an important concept in OOP, and full support for collections in C # is also one of the essence of the language.

Why use a generic set?

Before C #2.0, You can implement a set in two ways:

A. Use arraylist

Directly put the object into the arraylist. The operation is intuitive. However, because the items in the set are of the object type, you must perform tedious type conversion every time you use them.

B. Use a custom collection class

A common practice is to inherit a custom class from the collectionbase abstract class and encapsulate the ilist object to implement a strongly typed set. This method requires that a custom class be written for each set type, which requires a large workload. The emergence of generic sets effectively solves the above problem. You only need a line of code to create a set of the specified type.

What is generics?

Generics are new elements in C #2.0 (called templates in C ++) and are mainly used to solve a series of similar problems. This mechanism allows you to pass the class name as a parameter to the generic type and generate the corresponding object. The generic type (including classes, interfaces, methods, and delegation) can be better understood as a template. The variant part of the template will be replaced by the class name passed in as a parameter, to get a new type definition. Generic is a big topic. I will not elaborate on it here. If you are interested, please refer to the relevant materials.

 

 

How to Create a generic set?

The system. Collections. Generic namespace is used to create a set of list <t> generic classes. The syntax is as follows:

The person class is defined as follows:

As you can see, the generic set greatly simplifies the implementation code of the Set, through which you can easily create a set of the specified type. In addition, generic collections provide more powerful functions. Let's take a look at the sorting and search functions.

List <t> listoft = new list <t> ();

The "T" is the type to be used. It can be a simple type, such as string, Int, or user-defined type. The following is an example.

 

Class person

{

Private string _ name; // name

Private int _ age; // age

// Create a 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 a person object

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

Person P2 = new person ("Li Si", 20 );

Person P3 = new person ("Wang Wu", 50 );

// Create an object set of the person type

List <person> Persons = new list <person> ();

// Put the person object into the set

Persons. Add (P1 );

Persons. Add (P2 );

Persons. Add (P3 );

// Output the name of 2nd people

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

Sorting of generic Sets

Sorting is based on comparison. To sort, you must first compare. For example, if you want to sort two numbers 1 and 2, you must first compare them and sort them according to the comparison results. If you want to compare objects, the situation must be more complex. For example, to compare person objects, you can compare objects by name or by age, therefore, you need to determine the comparison rules. An object can have multiple comparison rules but only one default rule. 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. See 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 returned value is int type. If the returned value is greater than 0, the first object is greater than the second object. If the returned value is less than 0, indicates that the first object is smaller than the second object. If 0 is returned, the two objects are equal.

After defining the default comparison rule, you can sort the set by using the sort method without parameters, as shown below:

// Sort the set according to the default rules

Persons. Sort ();

// Output the name of the owner

Foreach (person P in persons)

{

Console. writeline (P. Name); // The output sequence is Li Si, Zhang San, and Wang Wu"

}

In actual use, it is often necessary to sort the set by multiple different rules. This requires defining other comparison rules, which can be defined in the compare method, this method belongs to the icomparer <t> generic interface. See the following code:

Class namecomparer: icomparer <person>

{

// Store the sorting server 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 objects of the same type to be compared, and the return value is of the int type. The return value processing rules are the same as those of the compareto method. Comparer. Default returns a built-in comparer object, which is used to compare two objects of the same type.

The following uses the new comparator to sort the set:

You can also sort sets by delegation. First, you must define a method for calling by delegation to store comparison rules. You can use static methods. See the following code: Then, use the built-in generic delegate system. Comparison <t> to sort the set:

We can see that the last two methods can sort the set according to the specified rules, but I prefer to use the delegate method. You can consider placing various comparison rules in one class, then make flexible calls.

// Sort the set by name

Persons. Sort (namecomparer. Default );

// Output the name of the owner

Foreach (person P in persons)

{

Console. writeline (P. Name); // The output sequence is Li Si, Wang Wu, and 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 objects of the same type to be compared, and the return value is of the int type. The return value processing rules are the same as those of the compareto method.

System. Comparison <person> namecomparison = new system. Comparison <person> (personcomparison. Name );

Persons. Sort (namecomparison );

// Output the name of the owner

Foreach (person P in persons)

{

Console. writeline (P. Name); // The output sequence is Li Si, Wang Wu, and Zhang San"

}

We can see that the last two methods can sort the set according to the specified rules, but I prefer to use the delegate method. You can consider placing various comparison rules in one class, then make flexible calls.

Search for generic Sets

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

Class personpredicate

{

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

Public static bool midage (person P)

{

If (P. age> = 40)

Return true;

Else

Return false;

}

}

The preceding search condition is placed in a static method. The return type of the method is boolean. If the set contains items that meet specific conditions, true is returned. 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 "Wang Wu"

} Then, use the built-in generic delegate system. predicate <t> to search for the set:

Extension of generic Sets

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

Considering that a single class can provide limited functions, it is natural to think of extending the list <t> class. generic classes are also classes, so they can be extended through inheritance. See the following code:

// Define the persons collection class

Class persons: List <person>

{

// Get the name of all users in the Set

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 fill in the persons set

Persons personcol = new persons ();

Personcol. Add (P1 );

Personcol. Add (P2 );

Personcol. Add (P3 );

// Output the name of the owner

Console. Write (personcol. getallnames (); // output "Zhang San, Li Si, Wang Wu"

List Method and attribute method or attribute function

Capacity is used to obtain or set the number of elements that a list can contain. When the quantity exceeds the capacity, this value automatically increases. 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 attribute, used to obtain the number of current elements in the array

Item () gets or sets the element through the specified index. For the List class, it is an indexer.

Add () Add a public method of an object to the list

Addrange () Public method. Multiple Elements implementing the icollection interface are added at the end of the list.

Binarysearch () is a public method that is overloaded. It is used to locate a specified element using binary search in the sorted list.

Clear () removes all elements from the list.

Contains () test whether an element is in the list

Copyto () overload public method, copy a list to a one-dimensional array

Exists () test whether an element is in the list

Find () finds and returns the First Matching Element in the list.

Findall () finds and returns all matching elements in the list.

Getenumerator () is a public method that is overloaded and returns an enumerator used to iterate the list.

Getrange () copies the elements in the specified range to the new list.

Indexof () is a public method that is overloaded. it searches for and returns the index of each matching element.

Insert () inserts an element into the list.

Insertrange () inserts a group of elements into the list.

Lastindexof () is a public method that is reloaded. it searches for and returns the index of the last matching element.

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

Removeat () removes the specified index element.

Removerange () Removes elements from a specified range.

Reverse () reverses the order of 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 introducing how to use the generic type in C #2.0 to implement the set, and how to expand the set function. Using the generic set appropriately can reduce a lot of repetitive work, greatly improve development efficiency. In fact, a collection is only a typical application of generics. If you want to learn more about generics, you can refer to other relevant materials. Hope this article is useful to you

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.