In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-19 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
This article will explain in detail what is the use of List in C#. The content of the article is of high quality, so the editor will share it with you for reference. I hope you will have some understanding of the relevant knowledge after reading this article.
1. # List generic collection
Collection is an important concept in OOP, and the full support for collections in C # is one of the essence of the language.
Why use 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 ListOfT = new List ()
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 persons = new List (); / / 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 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 generic interface. Take a look at the following code:
Class Person: IComparable {/ / compare public int CompareTo (Person p) {return this.Age-p.Age;} by age
The parameter of the CompareTo method is another object of the same type to be compared with, and the return value is of type int. If the return value is greater than 0, the first object is larger than the second object, if the return value is less than 0, the first object is smaller than the second object, and 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"}
The code is 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 generic interface. See the following code:
Class NameComparer: IComparer {/ / stores the collator instance public static NameComparer Default = new NameComparer (); / / compares 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 NameComparison = new System.Comparison (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"}
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 generic sets
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. The collection is then searched through the built-in generic delegate System.Predicate:
System.Predicate MidAgePredicate = new System.Predicate (PersonPredicate.MidAge); List MidAgePersons = persons.FindAll (MidAgePredicate); / / output all middle-aged names foreach (Person p in MidAgePersons) {Console.WriteLine (p.Name); / / output "Wang Wu"} extension of the generic set
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 class, and generic classes are also classes, so you can extend them through inheritance. Take a look at the following code:
/ / define the Persons collection class class Persons: List {/ / 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" II, List methods and attribute methods or attribute functions
Capacity is used to get or set the number of elements that List can hold. This value automatically increases when the quantity exceeds the capacity. You can set this value to reduce the capacity, or you can call the trin () method to reduce the capacity to suit the actual number of elements.
The Count attribute, which is 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 () adds a public method of an object to List
AddRange () public method, adding multiple elements that implement the ICollection interface at the end of the List
A public method overloaded by BinarySearch () that uses binary lookups to locate specified elements within a sorted List.
Clear () removes all elements within the List
Contains () tests whether an element is within the List
The public method overloaded by CopyTo (), which copies a List into an one-dimensional array
Exists () tests whether an element is within the List
Find () finds and returns the first matching element that appears in the List
FindAll () finds and returns all matching elements in List
The public method overloaded by GetEnumerator () returns an enumerator for iterating through List
Getrange () copies the specified range of elements into the new List
IndexOf () overloaded public method to find and return the index of each matching element
Insert () inserts an element into the List
InsertRange () inserts a set of elements into the List
The public method overloaded by LastIndexOf (), which finds and returns the index of the last matching element
Remove () removes the first element that matches the specified element
RemoveAt () removes the element of the specified index
RemoveRange () removes elements in the specified range
Reverse () reverses the order of elements in List
Sort () sorts the elements in the List
ToArray () copies the elements in List into a new array
TrimToSize () sets the capacity to the actual number of elements in the List
Third, the use of List 1, the basis of List, common methods: (1), declaration: ①, List mList = new List ()
T is the element type in the list, now take the string type as an example
List mList = new List (); ②, List testList = new List (IEnumerable collection)
Create a List with a collection as a parameter:
String [] temArr = {"Ha", "Hunter", "Tom", "Lily", "Jay", "Jim", "Kuku", "Locu"}; List testList = new List (temArr); (2), add element: ①, add an element
Grammar: List. Add (T item)
List mList = new List (); mList.Add ("John"); ②, add a set of elements
Grammar: List. AddRange (IEnumerable collection)
List mList = new List (); string [] temArr = {"Ha", "Hunter", "Tom", "Lily", "Jay", "Jim", "Kuku", "Locu"}; mList.AddRange (temArr); ③, add an element to the index location
Syntax: Insert (int index, T item)
List mList = new List (); mList.Insert (1, "Hei"); ④, elements in ergodic List
Syntax:
The type of foreach (T element in mList) / / T is the same as when mList declares {Console.WriteLine (element);}
Example:
List mList = new List ();... / / omit part of the code foreach (string s in mList) {Console.WriteLine (s);} (3), delete element: ①, delete a value
Grammar: List. Remove (T item)
MList.Remove ("Hunter"); ②, delete the element with the subscript index
Grammar: List. RemoveAt (int index)
MList.RemoveAt (0); ③, starting with the subscript index, delete count elements
Grammar: List. RemoveRange (int index, int count)
MList.RemoveRange (3, 2); (4), determine whether an element is in the List:
Grammar: List. The returned value of Contains (T item) is: true/false
If (mList.Contains ("Hunter")) {Console.WriteLine ("There is Hunter in the list");} else {mList.Add ("Hunter"); Console.WriteLine ("Add Hunter successfully.");} (5), sort the elements in the List:
Grammar: List. Sort () defaults to the ascending order of the first letter of the element
MList.Sort ()
Custom rule sorting
/ ① generic customization / list.Sort ((left, right) = > {if (left.n > right.n) / / where n is an attribute you want to sort by / / sort it in n order from smallest to largest; if you want to sort from big to small, change here to left.n
< right.n return 1; else if (left.n == right.n) return 0; else return -1;});/// /// ②针对属性是字符串的排序/// list.Sort((left, right) =>{return left.Date.CompareTo (right.Date); / / where Date is a time string}); (6) reverse the order of the elements in the List:
Grammar: List. Reverse () can be used with List. Sort () is used together to achieve the desired effect.
MList. Reverse (); (7), List clear:
Grammar: List. Clear ()
MList.Clear (); (8), get the number of elements in List:
Grammar: List. Count () returns an int value
Int count = mList.Count (); Console.WriteLine ("The num of elements in the list:" + count); 2. Advanced and powerful methods of List:
The List used for example in this paragraph:
String [] temArr = {"Ha", "Hunter", "Tom", "Lily", "Jay", "Jim", "Kuku", "Locu"}; mList.AddRange (temArr); (1), List.FindAll method: retrieves all elements that match the conditions defined by the specified predicate
Syntax: public List FindAll (Predicate match)
List subList = mList.FindAll (ListFind); / / delegate to the ListFind function foreach (string s in subList) {Console.WriteLine ("element in subList:" + s);}
At this point, subList stores all elements with a length greater than 3.
(2) the List.Find method: searches for elements that match the criteria defined by the specified predicate and returns the first matching element in the entire List.
Syntax: public T Find (Predicate match)
Predicate is a delegate to a method that returns true if the object passed to it matches the condition defined in the delegate. The elements of the current List are passed one by one to the Predicate delegate and move forward in List, starting with the first element and ending with the last element. Processing stops when a match is found.
Predicate can delegate to a function or a Ramda expression:
Delegate to Ramda expression:
String listFind = mList.Find (name = > / / name is a variable, representing the element in mList, set {if (name.Length > 3) {return true;} return false;}); Console.WriteLine (listFind); / / output is Hunter
Delegate to a function:
String listFind1 = mList.Find (ListFind); / / delegated to ListFind function Console.WriteLine (listFind); / / output is Hunter//ListFind function public bool ListFind (string name) {if (name.Length > 3) {return true;} return false;}
The results of the two methods are the same.
(3) List.FindLast method: searches for the element that matches the condition defined by the specified predicate and returns the last matching element in the entire List.
Syntax: public T FindLast (Predicate match)
The usage is the same as List.Find.
(4) List.TrueForAll method: determines whether each element in List matches the condition defined by the specified predicate.
Syntax: public bool TrueForAll (Predicate match)
Delegate to Ramda expression:
Bool flag = mList.TrueForAll (name = > {if (name.Length > 3) {return true;} else {return false;}}); Console.WriteLine ("True for all:" + flag); / / the value is
Delegate to a function, where the above ListFind function is used:
Bool flag = mList.TrueForAll (ListFind); / / delegate to the ListFind function Console.WriteLine ("True for all:" + flag); / / the value is false
The results of the two methods are the same.
(5) List.Take (n) method: get the type of IEnumetable,T returned in the first n lines as the type of List (5); foreach (string s in takeList) {Console.WriteLine ("element in takeList:" + s);}
At this point, the elements stored in takeList are the first five elements in mList.
(6) List.Where method: retrieves all elements that match the conditions defined by the specified predicate. Similar to the List.FindAll method. IEnumerable whereList = mList.Where (name = > {if (name.Length > 3) {return true;} else {return false;}}); foreach (string s in subList) {Console.WriteLine ("element in subLis");}
At this point, subList stores all elements with a length greater than 3.
(7) the List.RemoveAll method removes all elements that match the conditions defined by the specified predicate.
Syntax: public int RemoveAll (Predicate match)
MList.RemoveAll (name = > {if (name.Length > 3) {return true;} else {return false;}}); foreach (string s in mList) {Console.WriteLine ("element in mList:" + s);}
At this point, mList stores elements whose length is greater than 3.
(8) List.Except () method to find the difference set of two List.
Syntax: ListA.Except (ListB). ListA and ListB represent the same type of List collection data, which returns a collection of elements that are in ListA but not in ListB.
List list1 = new List {1, 2, 3, 4}; List list2 = new List {3, 4, 5, 6}; List exceptList = list1.Except (list2). ToList (); the result set is: the exceptList set contains two elements, 1 and 2. So much for sharing about the usage of List in C#. I hope the above content can be helpful to you and learn more knowledge. If you think the article is good, you can share it for more people to see.
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.