In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-28 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
This article mainly explains "the collation of relevant knowledge points of C# generics set". The content of the explanation in this article is simple and clear, and it is easy to learn and understand. let's study and learn "collation of relevant knowledge points of C# generics set"!
Why use C # generic collections?
Prior to C # 2.0, collections could be implemented in two main ways:
a. Use ArrayList
Putting objects directly into the ArrayList is intuitive, but because the items in the collection are of type Object, you have to do tedious type conversions each time you use them.
b. Use custom collection classes
It is common to inherit a custom class from the CollectionBase abstract class and implement a strongly typed collection by encapsulating the IList object. This approach requires writing a corresponding custom class for each collection type, which requires a large amount of work. The emergence of generic collections solves the above problems well, and it only takes a single line of code to create a collection of a specified type.
What is generics?
Generics are a new element 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. It may be better to think of generics (including classes, interfaces, methods, delegates, etc.) as templates, and the variant parts of the template will be replaced by the class name passed in as parameters, resulting in a new type definition. Generics is a relatively large topic, which will not be analyzed in detail here. Those who are interested can consult the relevant information.
How do I create a generic collection?
The collection is mainly created using the List generic class under the System.Collections.Generic namespace. The syntax is as follows:
List < T > ListOfT = new List < T > ()
The "T" is the type to be used, which can be either a simple type, such as string, int, or a user-defined type. Let's look at a specific example.
The Person class is defined as follows:
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 objects Person p1 = new Person ("Zhang San", 30); Person p2 = new Person ("Li Si", 20); Person p3 = new Person ("Wang Wu", 50); / / create a collection of objects of type Person List < Person > persons = new List < Person > (); / / put Person objects into the collection persons.Add (p1); persons.Add (p2); persons.Add (p3) / / output the name of the second person Console.Write (persons [1] .Name)
As you can see, generic collections greatly simplify the implementation code of collections, through which you can easily create collections of a specified type. Not only that, generic collections provide more powerful functionality, let's take a look at sorting and searching.
Sorting of C # generic sets
Sorting is based on comparison. To sort, you must first compare. For example, if there are two numbers 1 and 2, if you want 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, so you need to determine the comparison rules. An object can have more than one comparison rule, but only one default rule, which 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 public int CompareTo by age (Person p) {return this.Age-p.Age;}}
The parameter of the CompareTo method is another object of the same type to be compared with, and the return value is int. If the return value is greater than 0, it means that * objects are larger than the second object. If the return value is less than 0, it means that * objects are smaller than the second object. If 0 is returned, the two objects are equal.
Once the default comparison rule is defined, the collection can be sorted by the Sort method with no parameters, as follows:
/ sort the collection according to the default rules persons.Sort (); / output the owner's name foreach (Person p in persons) {Console.WriteLine (p.Name); / / the output order is "Li Si", "Zhang San", "Wang Wu"}
In practice, you often need to sort collections according to many different rules, so you need to define other 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 > {/ / store sorter instance public static NameComparer Default = new NameComparer (); / / compare public int Compare (Person p1, Person p2) {return System.Collections.Comparer.Default.Compare (p1.Name, p2.Name);}} by name
The parameters of the Compare method are two objects of the same type to be compared, the return value is of type int, and the return value processing rules are the same as the CompareTo method. The Comparer.Default returns a built-in Comparer object for comparing two objects of the same type.
The collection is sorted with the newly defined comparator:
/ / sorts the collection by name persons.Sort (NameComparer.Default); / / outputs the owner's name foreach (Person p in persons) {Console.WriteLine (p.Name); / / the output order is "Li Si", "Wang Wu", "Zhang San"}
You can also sort collections through delegates. First, you need to define a method to be called by the delegate, which is used to store comparison rules. Static methods can be used. Take a look at the following code:
Class PersonComparison {/ / compare public static int Name by name (Person p1, Person p2) {return System.Collections.Comparer.Default.Compare (p1.Name, p2.Name);}}
The parameters of the method are two objects of the same type to be compared, the return value is of type int, and the processing rules of the return value are the same as the CompareTo method. The collection is then sorted through the built-in generic delegate System.Comparison:
System.Comparison < Person > NameComparison = new System.Comparison < Person > (PersonComparison.Name); persons.Sort (NameComparison); / output owner's name foreach (Person p in persons) {Console.WriteLine (p.Name); / / output order is "Li Si", "Wang Wu", "Zhang San"}
As you can see, the latter two ways can sort the collection according to the specified rules, but the author prefers to use delegation, so we can consider putting all kinds of comparison rules in one class, and then call them flexibly.
Search for C # generic collections
Search is to find items from the collection that meet specific criteria. Multiple search criteria can be defined and invoked as needed. First, define the search criteria, as follows:
Class PersonPredicate {/ / find the middle-aged (over 40 years old) public static bool MidAge (Person p) {if (p.Age > = 40) return true; else return false;}}
The above search criteria are placed in a static method, the return type of the method is Boolean, and items in the collection that meet certain criteria return true, otherwise return false. Then search the collection through the built-in generic delegate System.Predicate < T >:
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"}
Extension of C # generic collection
What if you want to get the names of all the people in the collection, separated by commas?
Given the limited functionality that a single class can provide, it's natural to think of extending the List < T > class, which is also a class, so you can extend it through inheritance. Take a look at the following code:
/ / define the Persons collection class class Persons: List < Person > {/ / get all the names 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's name Console.Write (PersonCol.GetAllNames ()); / / output "Zhang San, Li Si, Wang Wu"
Summary:
This paper focuses on the use of generics in C# 2.0 to achieve the collection, and the expansion of the collection function, the proper use of generic sets can reduce a lot of repetitive work and greatly improve the efficiency of development. In fact, collections are just a typical application of generics, and if you want to learn more about generics, you can check out other relevant materials. I hope this article is useful to you: -)
Attached: complete procedure
Using System; using System.Collections.Generic; using System.Collections; using System.IO; class Person: IComparable
< 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 }} / / public int CompareTo (Person p) {return this.Age-p.Age;}} class NameComparer: IComparer
< Person>{/ / Store sorter instance public static NameComparer Default = new NameComparer (); / / compare public int Compare (Person p1, Person p2) {return System.Collections.Comparer.Default.Compare (p1.Name, p2.Name) by name;}} class PersonComparison {/ / compare public static int Name (Person p1, Person p2) {return System.Collections.Comparer.Default.Compare (p1.Name, p2.Name) by name }} class PersonPredicate {/ / find the middle-aged (over 40 years old) public static bool MidAge (Person p) {if (p.Age > = 40) return true; else return false }} public class test {public static void Main (string [] args) {/ / create Person objects Person p1 = new Person ("Zhang San", 30); Person p2 = new Person ("Li Si", 20); Person p3 = new Person ("Wang Wu", 50); / / create a collection of objects of type Person List
< Person>Persons = new List
< Person>(); / / put Person objects into collections persons.Add (p1); persons.Add (p2); persons.Add (p3); / / sort collections according to default rules persons.Sort () / / output owner's name foreach (Person p in persons) {Console.WriteLine (p.Name); / / output order is "Li Si", "Zhang San", "Wang Wu"} persons.Sort (NameComparer.Default) / / output the owner's name foreach (Person p in persons) {Console.WriteLine (p.Name); / / the output order is "Li Si", "Wang Wu", "Zhang San"} System.Comparison
< Person>NameComparison = new System.Comparison
< Person>(PersonComparison.Name); persons.Sort (NameComparison); / / output the owner's name foreach (Person p in persons) {Console.WriteLine (p.Name); / / the output order is "Li Si", "Wang Wu", "Zhang San"} 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"}} Thank you for your reading. The above is the content of "sorting out the relevant knowledge points of the C# generic set". After the study of this article, I believe you have a deeper understanding of the collation of the relevant knowledge points of the C# generic set, and the specific use still needs to be verified in practice. Here is, the editor will push for you more related knowledge points of the article, welcome to follow!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.