Namespace :System.Collections.Generic    

List<T> Class is ArrayList Generic equivalent class of class . This class uses an array whose size can be increased dynamically on demand IList<T> generic interface .

Benefits of generics : It is used for c# Programming object-oriented programs in language increases efficiency and flexibility . Value types are not forced to be boxed or unboxed , Or for reference types , Cast down , So the performance is improved .

Performance considerations : List[T] Two advantages

 

(1) In the decision to use IList<T> Still use ArrayList class ( Both have similar functions ) Time , remember IList<T> Classes perform better and are type safe in most cases .

(2) If yes IList<T> Type of class T Use reference type , The behavior of the two classes is exactly the same . however , If for type T Use value type , Then we need to consider the implementation and packing problems .

Add to ArrayList
Any reference or value type in is implicitly cast up to Object. If the item is of value type , Must be boxed when it is added to the list , Unboxing on Retrieval . Cast and boxing and unboxing operations degrade performance ; In cases where circular access to large collections is necessary , The effect of packing and unpacking is very obvious .--- Microsoft

1. Add element

(1)List. Add(T item)   Add an element ,E.g.:    mList.Add("John");

(2)List. AddRange(IEnumerable<T>collection)   Add a set of elements ,

E.g.: string[] temArr = { "Ha","Hunter", "Tom","Lily", "Jay","Jim", "Kuku",
 "Locu"};

          mList.AddRange(temArr);

(3) stay index Place to add an element , E.g.:    mList.Insert(1, "Hei");

2. Delete element

(1) Delete a value ,E.g.:   mList.Remove("Hunter");

(2) Delete subscript as index Elements of ,E.g.:   mList.RemoveAt(0);

(3) From subscript index start , delete count Elements ,  E.g.:   mList.RemoveRange(3, 2);

3. Sort elements

(1) By default, the first letter of an element is in ascending order ,E.g.:   mList.Sort();

(2) Reverse order ,E.g.:List. Reverse ()   ; Can be associated with List. Sort () Use together , Achieve the desired effect

4. Find element

(1)List.Find method : Searches for elements that match the criteria defined by the specified predicate , And return to the whole List First matching element in .

Predicate It's a delegation of methods , If the object passed to it matches the criteria defined in the delegate , Then the method returns true. current List
The elements of are passed to Predicate entrust , And List Move forward in , Start with the first element , To the end of the last element . Processing stops when a match is found .

public T Find(Predicate<T>match);

Delegate to ramda expression :

E.g.:

Delegate to a function :
1 string listFind1 = mList.Find(ListFind); // Entrusted to ListFind function 2
Console.WriteLine(listFind); // Output is Hunter 3 4 //ListFind function : 5 public bool
ListFind(string name) 6 { 7 if(name.Length > 3) 8 { 9 returntrue; 10 } 11
returnfalse; 12 }
The results of the two methods are the same .

List.FindLast method : Searches for elements that match the criteria defined by the specified predicate , And return to the whole List Last matching element in .

(2)List.TrueForAll method :   Determine if List Each element in matches the conditions defined by the specified predicate .

publicbool TrueForAll(Predicate<T> match);

Delegate to ramda expression :
1 bool flag=mList.TrueForAll(name=>) 2 { 3 if (name.Length>3) 4 { 5 return
true; 6 } 7 else 8 { 9 return false; 10 } 11 } 12 Console.WriteLine("True for
all:"+flag);//flag The value of is False
Delegate to a function , Here we use the above ListFind function :
1 bool flag = mList.TrueForAll(ListFind); // Entrusted to ListFind function 2
Console.WriteLine("True forall: "+flag); //flag The value is false
(3)List.FindAll method : Retrieves all elements that match the conditions defined by the specified predicate .

publicList<T>FindAll(Predicate<T> match);
1 E.g.: 2 3 List<string> subList =mList.FindAll(ListFind); // Entrusted to ListFind function 4
5 foreach (string s in subList) 6 7 { 8 9 Console.WriteLine("element in
subList: "+s); 10 11 } 12 13 // At this time subList What's stored is that all lengths are greater than 3 Elements of 14 15 //List.Take(n):
Before acquisition n That's ok The return value is IEnumetable<T>,T The type of List<T> Class of // Same type 16 17 E.g.: 18 19
IEnumerable<string>takeList= mList.Take(5); 20 21 foreach(string s intakeList)
22 23 { 24 25 Console.WriteLine("element in takeList: " + s); 26 27 } 28 29 //
At this time takeList The stored elements are mList Before in 5 individual
(3)List.Where method : Retrieves all elements that match the conditions defined by the specified predicate . Follow List.FindAll Similar approach .

(4)List.RemoveAll method : Removes all elements that match the conditions defined by the specified predicate .

 

C# List<T> Sorting summary

There are many ways to do that List Sort , This paper summarizes three methods , But multiple implementations .

<>1. Sort base types

Method 1 :

call sort method , If descending order is required , Reverse :
List<int> list = new List<int>(); list.Sort();// Ascending sort list.Reverse();// Reverse order
Method 2 :

use lambda expression , Put a minus sign in front of it and it's in descending order
List<int> list= new List<int>(){5,1,22,11,4}; list.Sort((x, y) =>
x.CompareTo(y));// Ascending order list.Sort((x, y) => -x.CompareTo(y));// Descending order
The next step is to sort the non basic types , Take a class for example .

<>2. get ready

First write a class for sorting , There are two properties in it , A construction method , Rewritten ToString method :
class People { private int _id; private string _name; public People(int
id,string name) { this._id = id; this.Name = name; } public int Id { get {
return _id; } set { _id = value; } } public string Name { get { return _name; }
set { _name = value; } } // rewrite ToString public override string ToString() {
return "ID:"+_id+" Name:"+_name; } }
And then add some random data , Still want to use Sort sort
List<People> list = new List<People>(); Random r = new Random(); // Add data
for(int i = 0; i < 10; i++) { int j = r.Next(0, 10); list.Add(new People(j,
"name" + j)); } Console.WriteLine(" Before sorting :"); foreach(var p in list) {
Console.WriteLine(p); } list.Sort();// sort Console.WriteLine(" After sorting :"); foreach
(var p in list) { Console.WriteLine(p); }
Unfortunately , Front output OK , It's not good to leave behind :

see Sort According to the source code, it has the following overloads :

The third and the fourth are about the same .

<>3. realization IComparable Interface

You can see that there is only one way , We just need to modify the class itself
class People: IComparable<People> { private int _id; private string _name;
public People(int id,string name) { this._id = id; this.Name = name; } public
int Id { get { return _id; } set { _id = value; } } public string Name { get {
return _name; } set { _name = value; } } // Rewritten CompareTo method , according to Id sort public int
CompareTo(People other) { if (null == other) { return 1;// Large null value , return 1 } //return
this.Id.CompareTo(other.Id);// Ascending order return other.Id.CompareTo(this.Id);// Descending order }
// rewrite ToString public override string ToString() { return "ID:"+_id+"
Name:"+_name; } }

<>4. realization IComparer Interface

Let's first look at this interface :
public interface IComparer<in T> { // Parameters: // x: // The first object
to compare. // // y: // The second object to compare. // // Returns: // A
signed integer that indicates the relative values of x and y, as shown in the
// following table.Value Meaning Less than zerox is less than y.Zerox equals
y.Greater // than zerox is greater than y. int Compare(T x, T y); }
Focus on return value , less than 0 representative x < y, be equal to 0 representative x=y, greater than 0 representative x > y.

Let's take a look at the implementation of the class , It's simple , A code :
class People:IComparer<People> { private int _id; private string _name; public
People() { } public People(int id,string name) { this._id = id; this.Name =
name; } public int Id { get { return _id; } set { _id = value; } } public
string Name { get { return _name; } set { _name = value; } } //Compare function public
int Compare(People x, People y) { return x.Id.CompareTo(y.Id);// Ascending order }
// rewrite ToString public override string ToString() { return "ID:"+_id+"
Name:"+_name; } }
But it's not over , We actually used the 2 The first overloaded method , therefore List Parameters are also required :
IComparer<People> comparer = new People(); list.Sort(comparer);
* 1
* 2
<>5. Simpler

Although there are not many interface codes for sorting , But sometimes it's just an occasional sort , It's not like modifying a class , What shall I do? ? There's a simpler way, of course , Commission and lambda expression :

So here's the code , Class does not need to be modified , It's just a delegate construct overload :
list.Sort( delegate(People p1,People p2) { return p1.Id.CompareTo(p2.Id);// Ascending order
} );
of course ,lambda Simpler expression implementation :
list.Sort((x,y)=> { return x.Id.CompareTo(y.Id); });
* 1
<>6.OrderBy method

This method will sort the list To the original list, You can give it to others .
list = list.OrderBy(o => o.Id).ToList();// Ascending order list = list.OrderByDescending(o
=> o.Id).ToList();// Descending order
<>7. Multi weight sorting

I know so much about sorting ( In fact, there are more ), And then there's another question , If you want to be ID Compare when the same Name, The code above needs to be changed .

among , Interface IComparable Write like this :
// Rewritten CompareTo method , according to Id sort public int CompareTo(People other) { if (null ==
other) { return 1;// Large null value , return 1 } // Equal to return 0 int re = this.Id.CompareTo(other.Id);
if (0 == re) { //id Same re comparison Name return this.Name.CompareTo(other.Name); } return
re; }
IComparer and delegate also lambda You can do this in :
public int Compare(People x, People y) { int re = x.Id.CompareTo(y.Id); if (0
== re) { return x.Name.CompareTo(y.Name); } return re; }
OrderBy It's a little different :
list = list.OrderBy(o => o.Id).ThenBy(o=>o.Name).ToList(); list =
list.OrderByDescending(o => o.Id).ThenByDescending(o=>o.Name).ToList();// Descending order
<>8. summary

Although said so many , In fact, there are three ways , Two interfaces and OrderBy method ,lambda Expressions just make the form simpler .

Technology
©2019-2020 Toolsou All rights reserved,
It's unexpected Python Cherry tree (turtle The gorgeous style of Library ) Some East 14 Pay change 16 salary , Sincerity or routine ? Browser kernel ( understand )java Four functional interfaces ( a key , simple )HashMap Explain in detail html Writing about cherry trees , Writing about cherry trees os Simple use of module