C # usage of generic List,

Source: Internet
Author: User

C # usage of generic List,

1. List <T> namespace:

System. Collections. Generic (Assembly: mscorlib)

Ii. List <T> description:

1) indicates the list of objects that can be accessed through indexes. It provides methods for searching, sorting, and operating the list. 2) is the generic equivalent class of the ArrayList class. 3) You can use an integer index to access the elements in this set. The index starts from scratch. 4) can receive null references (in VBNothing). 5) Allow repeated Elements

 

Iii. List <T> Constructor

 

Name Description
List <T> () Initialize a new instance of the List <T> class. The instance is empty and has the default initial capacity (0 ).
List <T> (IEnumerable <T>) Initializes a new instance of the List <T> class. This instance contains elements copied from the specified set and has sufficient capacity to accommodate the copied elements.
List <T> (Int32) A new instance of the initial List <T> class. The instance is empty and has the specified initial capacity.

Note: by default, when you add an element to the List <T>, the internal array is reassigned and the capacity is automatically increased as needed. If you can estimate the size of the Set, When you specify the initial capacity, you do not need to perform a large number of resizing operations when adding elements to the List <T>. This improves performance.

 

Iv. List <T> attributes

 

Name Description
Capacity Obtains or sets the total number of elements that the internal data structure can accommodate without resizing.
Count Obtains the number of elements actually contained in the List <T>.

Note: Capacity is the number of elements that can be stored before the List <T> needs to be adjusted, and Count is the number of actually stored elements in List <T>.

 

V. List <T> Method

 

Name Description
Add Add the object to the end of List <T>.
AddRange Add the elements of the specified set to the end of List <T>.
AsReadOnly Returns the read-only IList <T> packaging of the current set.
BinarySearch (T) Use the default comparator to search for an element in the entire sorted List <T> and return the index from scratch.
BinarySearch (T, IComparer <T>) Use the specified comparator to search for an element in the entire sorted List <T> and return the index of the element starting from scratch.
BinarySearch (Int32, Int32, T, IComparer <T>) Use the specified comparator to search for an element in the range of an element in the sorted List <T> and return the index of the element starting from scratch.
Clear Remove all elements from List <T>.
Contains Determines whether an element is in List <T>.
ConvertAll <TOutput> Convert the elements in the current List <T> to another type and return a List containing the converted elements.
CopyTo (T []) Copy the entire List <T> to a compatible one-dimensional array and place it from the beginning of the target array.
Exists Determine whether the List <T> contains elements that match the conditions defined by the specified predicate.
Find Search for the elements that match the conditions defined by the specified predicate, and return the First Matching Element in the entire List <T>.
FindIndex (Predicate <T>) Search for the elements that match the conditions defined by the specified predicate, and return the index from scratch for the First Matching Element in the entire List <T>.
ForEach Perform the specified operation on each element of the List <T>.
GetEnumerator Returns the List <T> enumerator.
IndexOf (T) Search for the specified object and return the index starting from scratch for the first matching item in the entire List <T>.
Insert Insert the element to the specified index of List <T>.
InsertRange Insert an element in the set to the specified index of List <T>.
LastIndexOf (T) Search for the specified object and return the index starting from scratch for the last matching item in the entire List <T>.
Remove Remove the first match of a specific object from List <T>.
Reverse () Reverse the order of elements in the entire List <T>.
Sort () Use the default comparator to sort the elements in the entire List <T>.
TrimExcess Set the capacity to the actual number of elements in the List <T> (if the number is smaller than a threshold ).
TrueForAll Determine whether each element in List <T> matches the conditions defined by the specified predicate.

Note: The "Predicate" is used in the preceding method description. The Predicate is the Predicate <T> delegate, which represents a set of methods. This method defines a set of conditions, and determine whether the specified parameter object meets these conditions. For details, see the sample program.

 

Vi. Examples of common methods

 

(1) Creation and initialization:

List <string> myList = new List <string> (); // The initial Capacity is zero List <string> myList2 = new List <string> (30 ); // The initial Capacity is 30 List <string> myList3 = new List <string> (new string [] {"1", "a", "2 ", "B"}); // The initial Capacity is 4, and the element has been copied

 

(2) Add an element List. Add (T item)

Mlist. Add ("d ");

 

(3) add a set Element

String [] Arr2 = {"f", "g". "h"}; mlist. AddRange (Arr2 );

 

(4) add an Insert (int index, T item) element to the index position)

Mlist. Insert (1, "p ");

 

(5) traverse elements in the List

Foreach (T element in mlist) T is of the same type as mlist declaration {Console. WriteLine (element );}

 

(6) Delete an element

List. Remove (T item) delete a value mlist. Remove ("");

List. RemoveAt (int index); Delete the element mlist. RemoveAt (0) whose subscript is index );
List. RemoveRange (int index, int count); start with subscript index, delete the count element mlist. RemoveRange );

 

(7) determine whether an element is in the List

List. Contains (T item) returns true or false

If (mlist. Contains "(" g ") Console. WriteLine (" g in the List "); else mlist. Add (" g ");

 

(8) Sort the elements in the List. List. Sort () by default, each letter of the element is sorted in ascending order.

Mlist. Sort ();

 

(9) The List. Reverse () can be used with List. Sort () to Reverse the element order in the List.

 

(10) List Clear List. Clear ()

Mlist. Clear ();

 

(11) Capacity and Count

1) the number of elements that can be stored before the Capacity needs to be adjusted; Count the number of actually stored elements. 2) Capacity is always greater than or equal to Count

 

7. Precautions for List <T>

 

1. The List <T> class uses both equal comparator and sort comparator.

Methods such as Contains, IndexOf, LastIndexOf, and Remove use equal comparator for list elements. The default equal comparator of type T is determined as follows. If type T implements the IEquatable <T> generic interface, the equal comparator is the Equals (T) method of the interface. Otherwise, the default equality comparator is Object. Equals (Object ).

Methods such as BinarySearch and Sort use the Sort comparator for list elements. The default comparator of type T is determined as follows. If type T implements the IComparable <T> generic interface, the default comparator is the CompareTo (T) method of the interface. Otherwise, if type T implements the non-generic IComparable interface, the default comparator is the CompareTo (Object) method of this interface. If type T does not implement any of the interfaces, no default comparator exists and the comparator or comparison delegate must be explicitly provided.

2. List <T> is not necessarily ordered. Before you perform a List <T> sorted operation (such as BinarySearch), you must sort the List <T>.

3. List <T> is not necessarily ordered. Before you perform a List <T> sorted operation (such as BinarySearch), you must sort the List <T>.

4. You can use an integer index to access the elements in this set. The index in this set starts from scratch.

5. List <T> Accept null as the valid value of the reference type and allow repeated elements.

6. In most cases, List <T> performs better and is type-safe. You can replace ArrayList. However, if you use the value type for type T, the compiler will generate the List <T> class for this value type. This means that you do not need to bind the List element of the List <T> object to use this element. After about 500 List elements are created, the memory saved by packing the list elements is greater than the memory used to generate this class. If you create less than 500 elements, we recommend that you use ArrayList.


A simple program of C language Bubble Sorting

Main ()
{
Int I, j, temp;
Int a [10];
For (I = 0; I <10; I ++)
Scanf ("% d,", & a [I]);
For (j = 0; j <= 9; j ++)
{For (I = 0; I <10-j; I ++)
If (a [I]> a [I + 1])
{Temp = a [I];
A [I] = a [I + 1];
A [I + 1] = temp ;}
}
For (I = 1; I <11; I ++)
Printf ("% 5d,", a [I]);
Printf ("\ n ");
}

--------------
Bubble Algorithm
Algorithm Analysis and Improvement of Bubble Sorting
The basic idea of exchanging sorting is to compare the keywords of the records to be sorted in pairs. If the order of the two records is the opposite, the two records are exchanged until there is no reverse order record.
The basic concepts of application exchange sorting include Bubble sorting and quick sorting.

Bubble Sorting

1. Sorting Method
Vertically arrange the sorted record array R [1. n]. Each record R is considered as a bubble with the weight of R. key. According to the principle that a Light Bubble cannot be under a heavy bubble, scan the array R from the bottom up: Any Light Bubble scanned to a violation of this principle will make it "float" up ". This is repeated until the last two bubbles are light and heavy.
(1) initial
R [1. n] is an unordered area.

(2) First scan
The weights of two adjacent bubbles are compared from the bottom of the unordered area to the top. If the light bubbles are found to be in the lower and severe bubbles, the positions of the two bubbles are exchanged. That is, compare (R [n], R [n-1]), (R [n-1], R [N-2]),…, (R [2], R [1]); for each pair of bubbles (R [j + 1], R [j]), if R [j + 1]. key <R [j]. key, then the contents of R [j + 1] and R [j] are exchanged.
When the first scan is complete, the "lightest" bubble floated to the top of the interval, that is, the record with the smallest keyword is placed on the highest position R [1.

(3) second scan
Scan R [2. n]. When scanning is completed, the "light" bubble floated to the R [2] position ......
Finally, the sequential area R [1. n] can be obtained through n-1 scanning.
Note:
During the I-trip scan, R [1 .. I-1] and R [I.. n] are the current sequential and disordered areas, respectively. The scan continues from the bottom of the unordered area to the top of the area. When scanning is completed, the shortest bubbles in the area float to the top position R. The result is that R [1. I] is changed to a new ordered area.

2. Bubble sorting process example
Bubble Sorting of files whose keyword sequence is 49 38 65 97 76 13 27 49

3. Sorting Algorithm
(1) Analysis
Because each sort adds a bubble to the ordered area, there are n-1 bubbles in the ordered area after N-1 sort, in the disordered area, the bubble weight is always greater than or equal to the bubble weight in the ordered area. Therefore, the entire Bubble sorting process requires at most n-1 sorting.
If no bubble position exchange is found in a sorting, it means that all bubbles in the unordered area to be sorted meet the principle of being light and heavy. Therefore, the Bubble sorting process can be terminated after this sorting. Therefore, in the following algorithm, a Boolean exchange is introduced, which is set to FALSE before each sort starts. If an exchange occurs during the sorting process, set it to TRUE. Check exchange at the end of sorting. If exchange has not occurred, terminate the algorithm and no longer perform the next sorting.

(2) specific algorithms
Void BubbleSort (SeqList R)
{// R (l. n) is the file to be sorted. It uses bottom-up scanning to perform Bubble Sorting on R.
Int I, j;
Boolean exchange; // exchange flag
For (I = 1; I <G id = "1">

A simple program of C language Bubble Sorting

Main ()
{
Int I, j, temp;
Int a [10];
For (I = 0; I <10; I ++)
Scanf ("% d,", & a [I]);
For (j = 0; j <= 9; j ++)
{For (I = 0; I <10-j; I ++)
If (a [I]> a [I + 1])
{Temp = a [I];
A [I] = a [I + 1];
A [I + 1] = temp ;}
}
For (I = 1; I <11; I ++)
Printf ("% 5d,", a [I]);
Printf ("\ n ");
}

--------------
Bubble Algorithm
Algorithm Analysis and Improvement of Bubble Sorting
The basic idea of exchanging sorting is to compare the keywords of the records to be sorted in pairs. If the order of the two records is the opposite, the two records are exchanged until there is no reverse order record.
The basic concepts of application exchange sorting include Bubble sorting and quick sorting.

Bubble Sorting

1. Sorting Method
Vertically arrange the sorted record array R [1. n]. Each record R is considered as a bubble with the weight of R. key. According to the principle that a Light Bubble cannot be under a heavy bubble, scan the array R from the bottom up: Any Light Bubble scanned to a violation of this principle will make it "float" up ". This is repeated until the last two bubbles are light and heavy.
(1) initial
R [1. n] is an unordered area.

(2) First scan
The weights of two adjacent bubbles are compared from the bottom of the unordered area to the top. If the light bubbles are found to be in the lower and severe bubbles, the positions of the two bubbles are exchanged. That is, compare (R [n], R [n-1]), (R [n-1], R [N-2]),…, (R [2], R [1]); for each pair of bubbles (R [j + 1], R [j]), if R [j + 1]. key <R [j]. key, then the contents of R [j + 1] and R [j] are exchanged.
When the first scan is complete, the "lightest" bubble floated to the top of the interval, that is, the record with the smallest keyword is placed on the highest position R [1.

(3) second scan
Scan R [2. n]. When scanning is completed, the "light" bubble floated to the R [2] position ......
Finally, the sequential area R [1. n] can be obtained through n-1 scanning.
Note:
During the I-trip scan, R [1 .. I-1] and R [I.. n] are the current sequential and disordered areas, respectively. The scan continues from the bottom of the unordered area to the top of the area. When scanning is completed, the shortest bubbles in the area float to the top position R. The result is that R [1. I] is changed to a new ordered area.

2. Bubble sorting process example
Bubble Sorting of files whose keyword sequence is 49 38 65 97 76 13 27 49

3. Sorting Algorithm
(1) Analysis
Because each sort adds a bubble to the ordered area, there are n-1 bubbles in the ordered area after N-1 sort, in the disordered area, the bubble weight is always greater than or equal to the bubble weight in the ordered area. Therefore, the entire Bubble sorting process requires at most n-1 sorting.
If no bubble position exchange is found in a sorting, it means that all bubbles in the unordered area to be sorted meet the principle of being light and heavy. Therefore, the Bubble sorting process can be terminated after this sorting. Therefore, in the following algorithm, a Boolean exchange is introduced, which is set to FALSE before each sort starts. If an exchange occurs during the sorting process, set it to TRUE. Check exchange at the end of sorting. If exchange has not occurred, terminate the algorithm and no longer perform the next sorting.

(2) specific algorithms
Void BubbleSort (SeqList R)
{// R (l. n) is the file to be sorted. It uses bottom-up scanning to perform Bubble Sorting on R.
Int I, j;
Boolean exchange; // exchange flag
For (I = 1; I <G id = "1">

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.