10. C # basic sorting (SET ),
Set 1. Set Reference
Using System. Collections; // Add a class
2. Define a set (ArrayList or Array)
ArrayList arr = new ArrayList();
3. Add data (multiple data types can be put, but only one data type is recommended) (1) Single Data
Method 1:Add
arr.Add(3);arr.Add(5);arr.Add("hello");
Output result:
Console. writeLine ("add [0]:" + arr [0]); // an index starting from 0 is generated sequentially by adding elements, and data is read through the index, the output is "3" Console. writeLine ("add [1]:" + arr [1]); // 5Console. writeLine ("add [2]:" + arr [2]); // hello
Method 2:Insert to move the data starting from the index one bit backward
Arr. Insert (1, 17); // Insert (index, inserted data)
Output result:
Console.WriteLine("insert[0]"+arr[0]);//3Console.WriteLine("insert[1]" + arr[1]);//17Console.WriteLine("insert[2]" + arr[2]);//5Console.WriteLine("insert[3]" + arr[3]);//hello
(2) array:
1. append a set of data addrange
int[] shuzu = new int[3] { 6, 7, 8 };arr.AddRange(shuzu);
Traversal:
Foreach (object o in arr) // because there may be multiple types of data in the collection, the object (base class) should be used for traversal. All types can be converted to this type {Console. writeLine ("traversal 1:" + o );}
2. Insert a group of data InsertRange from the specified index
Arr. InsertRange (2, shuzu); // traverse foreach (object o in arr) {Console. WriteLine ("traversal 2:" + o );}
4. Remove Data: (only the first matching item is removed)
(1) Remove the specified data (value): Remove
Arr. Remove (17); // Remove the data foreach (object o in arr) {Console. WriteLine ("Remove:" + o );}
(2) Remove the element at the specified index location: RemoveAt
Arr. RemoveAt (2); Console. WriteLine ("Data indexed as [3] After removing:" + arr [3]);
5. Sorting:
(1) sort: automatically arranged in ascending order
ArrayList arr1 = new ArrayList (); for (int I = 0; I <5; I ++) {arr1.Add (int. parse (Console. readLine ();} arr1.Sort (); foreach (object o in arr1) {Console. writeLine ("ascending sort:" + o );}
(2) Reverse: sorting of the flipped set (turning it into descending order)
Arr1.Reverse (); foreach (object o in arr1) {Console. WriteLine ("reverse:" + o );}
6. Set attributes:
Count: returns the number of elements in the set.
Console. WriteLine ("number of elements:" + arr1.Count );
7. Return Index IndexOf
Console. writeLine ("the index of hello is:" + arr. indexOf ("hello"); // returns only the index Console of the first matching item. writeLine ("the index of the last match where hello is located is:" + arr. lastIndexOf ("hello"); // returns the index of the last match.
** The inserted array indexes are also arranged by a single data. For example, if you insert a group of three arrays, three indexes will be created.
8. contains: determines whether an element exists and returns the bool value.
Arr. Contains (1 );
9. Clear the set
Arr. Clear ();