[Reading Notes] C # advanced programming Chapter 6 array,

Source: Internet
Author: User
Tags element groups

[Reading Notes] C # advanced programming Chapter 6 array,

(1)Multiple objects of the same type and different types

If you need to use multiple objects of the same type, you can use arrays or collections (as described in the following chapter ).

To use multiple objects of different types, you can use the Tuple (tuples) type.

 

 

(2)Simple Array

If you want to use multiple objects of the same type, you can use arrays. An array is a structure that can contain multiple elements of the same type.

 

1,Array declaration

When declaring an array, you should first define the type of the array's total elements, followed by a bunch of empty square brackets and a variable name.

Example:

The following Code declares an array containing an integer type

int[] intArray;

 

2,Array Initialization

After declaring an array, you must allocate memory to the array to save all elements of the array. The array is of the reference type, so the memory on the stack needs to be allocated. Therefore, the new Keyword should be used to specify the type and quantity of elements in the array to initialize the variable of the array.

Example:

intArray = new int[10];

In addition to the above initialization methods, there are also the following methods:

int[] intArray = new int[10] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 0 };int[] intArray = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 0 };int[] intArray = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 0 };

 

3,Access array elements

After declaring and initializing the array, you can use the indexer to access the element. Arrays only support indexers with Integer Parameters.

You can access the array by passing the element number through the indexer. The indexer always starts with 0, indicating the first element. The maximum value that can be passed to the indexer is 1 minus the number of elements, because the index starts from 0.

int[] intArray = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 0 };int x = intArray[6];//7int y = intArray[9];//0

You can also use for loop access:

for (int i = 0; i < intArray.Length; i++){    Console.WriteLine(intArray[i]);}

In addition to the for loop, you can also use the foreach loop:

foreach (var item in intArray){    Console.WriteLine(item);}

 

4,Use reference type

In addition to declaring pre-defined arrays, you can also declare arrays of custom types.

Person[] personArray = new Person[3];

After initialization, you can use the indexer to assign values to elements:

personArray[0] = new Person();personArray[1] = new Person();personArray[2] = new Person();

 

 

 

(3)Multi-dimensional array

An array (also called a one-dimensional array) is indexed by an integer. Multi-dimensional arrays are indexed by two or more integers.

To declare a multi-dimensional array, add a comma in square brackets.

Example:

Declare a two-dimensional array

int[,] intTwoDim = new int[3, 3];intTwoDim[0, 0] = 1;intTwoDim[0, 1] = 2;intTwoDim[0, 2] = 3;intTwoDim[1, 0] = 4;intTwoDim[1, 1] = 5;intTwoDim[1, 2] = 6;intTwoDim[2, 0] = 7;intTwoDim[2, 1] = 8;intTwoDim[2, 2] = 9;

Example:

Declare a 3D Array

int[,,] intTwoDim = new int[2, 2, 2];intTwoDim[0, 0, 1] = 1;intTwoDim[0, 0, 2] = 2;intTwoDim[0, 1, 1] = 3;intTwoDim[0, 1, 2] = 4;intTwoDim[0, 2, 1] = 5;intTwoDim[0, 2, 2] = 6;intTwoDim[1, 0, 1] = 7;intTwoDim[1, 0, 2] = 8;intTwoDim[1, 1, 1] = 9;intTwoDim[1, 1, 2] = 10;intTwoDim[1, 2, 1] = 11;intTwoDim[1, 2, 2] = 12;intTwoDim[2, 0, 1] = 13;intTwoDim[2, 0, 2] = 14;intTwoDim[2, 1, 1] = 15;intTwoDim[2, 1, 2] = 16;intTwoDim[2, 2, 1] = 17;intTwoDim[2, 2, 2] = 18;

Note that after an array is declared, its order cannot be modified. When an array is initialized, each element of the array must be initialized and no element can be left.

 

 

(4)Sawtooth Array

The size of a multi-dimensional array corresponds to a rectangle, and the size setting of the Sawtooth array is flexible. In the Sawtooth array, each row can have different sizes.

When declaring a sawtooth array, place the left and right parentheses at a time. When initializing a sawtooth array, set the number of rows contained in the array in the first square brackets. The 2nd square brackets that define the number of elements in each row are set to null, because the number of elements in each row of this type of array may be different and must be assigned a value using the indexer.

Example:

int[][] intJagged = new int[2][];intJagged[0] = new int[1] { 1 };intJagged[1] = new int[5] { 1, 2, 3, 4, 5 };intJagged[2] = new int[2] { 1, 2 };

 

 

(5)Array class

Using square brackets to declare an Array is actually the representation of the Array class in C.

1,Create an array

The Array class is an abstract class, so you cannot use constructors to create arrays. However, in addition to using the C # syntax to create an array, you can also use the static CreateInstance () method to create an array.

Example:

Array intArray = Array. createInstance (typeof (int), 2); // create an array intArray. setValue (1, 0); // use setvalue to assign values to intArray. setValue (2, 1); int [] intNewArray = (int []) intArray; // can be converted to the int [] Form

 

2,Copy an array

Because the array is a reference type, if you assign an array variable to another array variable, two variables that reference the same array will be obtained. You can use the Clone () method or the Copy () method to Copy an array. The difference is that the Clone () method creates a new array, while the Copy () method () methods must pass existing arrays with the same order and sufficient elements, but they are all superficial copies.

To include a deep copy of an array of the reference type, you must iterate the array and create a new object.

 

3,Sort

The Array class uses the QuickSort algorithm to sort the elements in the Array. The Sort method requires array elements to implement the IComparable interface, because simple types (string, int) implement this interface, so it can be sorted. However, the custom type can be sorted only by implementing the IComparable interface.

Example:

int[] intArray = { 21,3291,12,392,39,92,193};Array.Sort(intArray);foreach (var item in intArray){    Console.WriteLine(item);}

Run the above Code and the result is as follows:

 

 

 

(6)Array as a parameter

Arrays can be passed to methods as parameters or returned from methods.

Example:

public static int[] ArraySort(int[] array){    Array.Sort(array);    return array;}

1,Array covariant

The array supports covariant. This indicates that an array can be declared as a base class, and elements of its derived type can be assigned to an array element. But the array covariant can only be used for reference type, not for value type. In addition, if the parameters passed in by the array covariant cannot meet the conditions in the method, an exception can only be thrown during running.

 

2,ArraySegment <T>

The ArraySegment structure <T> indicates an array segment, which contains information about the offset of the array segment and the number of elements.

Example:

int[] intArray = { 0, 1, 2, 3, 4, 5 };var intArraySegment = new ArraySegment<int>(intArray, 2, 2);foreach (var item in intArraySegment){    Console.WriteLine(item);}

Run the above Code and the result is as follows:

 

Note that the array segment does not copy the elements of the original array.

 

(7)Enumeration

1,IEnumerator Interface

The foreach statement uses the methods and attributes of the IEnumerator interface to iterate all elements in the set.

The IEnumerator <T> interface of the generic version is derived from IDisposable. Therefore, the Dispose () method is defined to clear the resources occupied by the enumerator.

 

2,Foreach statement

C # The Compiler converts the foreach statement into the methods and attributes of the IEnumerable interface.

Example:

foreach (var item in intArray){    Console.WriteLine(item);}

The compiler parses the foreach statement:

IEnumerator<int> enumerator = intArray.GetEnumerator();while (enumerator.MoveNext()){    int i = enumerator.Current();    Console.WriteLine(i);}

 

3,Yield statement

C #2.0 added the yield statement to facilitate the creation of the enumerator. The yield return Statement returns an element of the set and moves it to the next element. Yield break can stop iteration.

Example:

First, define a GetEnumertor method whose return type is IEnumertor <T>.

Public class PersonCollection {public IEnumerator <string> GetEnumerator () {yield return "Zhang San"; yield return "Li Si"; yield return "Wang Ma Zi"; yield return "Zhao Liu ";}}

Then you can use the foreach statement to iterate the set.

PersonCollection personCollection = new PersonCollection();foreach (var item in personCollection){    Console.WriteLine(item);}

Run the above Code and the result is as follows:

 

The yield statement generates an enumerator instead of a list of included items. This enumerator is called using the foreach statement. When you access each item sequentially from foreach, the enumerator is accessed. In this way, a large amount of data can be iterated without the need to read all the data into the memory at one time.

 

 

(8)Tuples

Arrays merge objects of the same type, and tuples merge objects of different types .. NET Framework defines eight generic Tuple classes and a static Tuple class, which are used as the factory of tuples. Tuples are created using the static Create () method of the static Tuple class.

Var result = Tuple. create <int, int> (1, 2); // Create two parameter tuples var result1 = Tuple. create <int, Tuple <int, int, int> (1, 2, 3, 4, 5, 6, 7, tuple. create <int, int, int> (8, 9, 0); // Create the tuples var result_item = result for 10 (more than 7) parameters. item1; var result1_item10 = result1.Rest. item1.Item3; // access the first parameter of the Two Parameter tuples

 

 

(9) structure comparison

Both arrays and element groups implement the IStructuralEquatable and IStructuralComparable interfaces. Both interfaces are added to. NET 4. They can be referenced and compared. These interfaces are all display implementations, so you need to forcibly convert the array and element group into this interface during use. The IStructuralEquatable interface is used to compare whether two tuples or arrays have the same content. The IStructuralComparable interface is used to sort tuples or arrays.

 

(10)Summary

This chapter describes how to create and use C # notation for simple arrays, multi-dimensional arrays, and sawtooth arrays. C # The Array uses the Array class in the background, so that you can use the Array variable to call the attributes and methods of this class.

This article discusses how to use the IComparable and IComparaer interfaces to sort elements in the array, describes how to use and create enumerators, IEnumerable and IEnumerator interfaces, and yield statements.

Finally, this article describes how to organize objects of the same type in arrays and organize objects of different types in tuples.

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.