C # array Summary

Source: Internet
Author: User

I. array-array
 
The method for defining an array in C # is generally:
 
Data Type [] array = new datatype [size];
 
Data type can be basic data type and object type data, and size is the number of array elements.
 
The example defines an int type to indicate the number of students in a class.
 
Int [] classnum = new int [20];
 
The attributes of the array include:
 

Attribute

Meaning

 

Public Virtual bool isfixedsize

Whether the array length is fixed

 

Public Virtual bool isreadonly

Whether the array is read-only

 

Public Virtual bool issynchronized

Secure in multi-threaded Environments

 

Public int Length

Number of array elements

 

Public int rank

Array dimension

 

Public Virtual Object syncroot

Synchronous access to array objects

 
The methods of array objects include static methods and instance methods;
 
Public static int binarysearch (array A, object V );
 
Array A must be one-dimensional and sorted. The result of this method is to return the index number of the first element matching V in array A. If no matching element exists, a negative number-1 is returned;
 
Public static int binarysearch (array A, object v, icomparer comp );
 
Similar to the preceding method, the difference is that comp is used to compare symbols;
 
Public static int binarysearch (array A, int start, int count, object V)
 
Query an index number of the element matching V from the count element starting from start in.
 
Public static int binarysearch (array A, int start, int count, object v, icomparer comp)
 
Similar to the previous method, the difference is that the comparative method is used for compensation;
 
Public static void clear (array A, int start, int count)
 
Set the Count elements starting from start in array a to zero;
 
Public Virtual Object clone () copy this array;
 
Public static void copy (array source, array DEST, int count)
 
Assign the Count elements in source to the array DeST .;
 
Public Virtual void copyto (array DEST, int start)
 
Assign the Start Element in the array object that calls this method to DeST.
 
Public static array createinstance (type T, int size)
 
Create an array with size elements. The element type is T;
 
Public static array createinstance (type T, int size1, int size2)
 
Create a two-dimensional array. The array parameter is [size1] [size2]; The array element type is t;
 
Public static array createinstance (type T, int size1, int size2, int size3)
 
Create a 3D array with the element type T, the same as creating a 2D array .;
 
Public static array createinstance (type T, int [] sizes)
 
Create an array with the sizes dimension parameter. The element type is T;
 
Public static array createinstance (type T, int [] sizes, int [] startindexes)
 
Create a multi-dimensional array. The array dimension is sizes, and the Data Type of each element is T. The starting index number of each one-dimensional array in the array is startindexes;
 
Public override bool equals (Object V)
 
Determine whether V is the same as the array object that calls this method.
 
Public Virtual ienumerator getenumerator ()
 
Returns the enumerated object of the array.
 
Public int getlength (INT dim)
 
Returns the number of dim elements in a multi-dimensional array.
 
Public override int gethashcode ()
 
Returns the array hash code;
 
Public int getupperbound (INT dim)
 
Returns the last index value of the dim Dimension Element of a multi-dimensional array.
 
Public object getvalue (INT index) returns the value of the index element of the one-dimensional array.
 
Public object getvalue (INT idx1, int idx2) and public object getvalue (INT idx1, int idx2, int idx3) obtain the values of a special element in the two-dimensional and three-dimensional arrays respectively .;
 
Public static int indexof (array A, object v) returns the index value of the first element with the same value as v in;
 
Public static int indexof (array A, object v, int start)
 
Starting from the Start Element in A, return the same element position as the value of V;
 
Public static int indexof (array A, object v, int start, int count)
 
Return the same element position as the value of V from the count element starting with the start element in;
 
Public static int lastindexof (array A, object v, int start, int count)
 
Search for the index number of the element equal to V in the count element starting with the Start Element in.
 
Public static void reverse (array a) reverses all elements of array;
 
Public void setvalue (Object V, int index) sets the value of the index element of the array object to V;
 
Similar functions are available for object 2D and 3D arrays; Public void setvalue (Object V, int idx1, int idx2) and Public void setvalue (Object V, int idx1, int idx2, int idx3)
 
Public static void sort (array a) sorts array;
 
2. Define and initialize an array
 
Int [] myintarray; myintarray = new int [4]; uses the Array Function indexof () and lastindexof () to obtain the position of a specific element in the array;
 

Int [] intarray = {1, 2, 1, 3 };
Console. writeline ("intarray :");

For (INT I = 0; I <intarray. length; I ++)

{

Console. writeline ("intarray [" + I + "] =" +

Intarray [I]);}

Int Index = array. indexof (intarray, 1 );

Console. writeline ("array. indexof (intarray, 1) =" + index );

Index = array. lastindexof (intarray, 1 );

Console. writeline ("array. lastindexof (intarray, 1) =" + index );
 

I. C # attributes of Arrays
 
The attributes and methods of one-dimensional arrays and multi-dimensional arrays are similar, mainly because some parameters of the array method are inconsistent, now let's take a look at the relevant attributes of the one-dimensional array;
 
Int [] Myint = new int [5];
 
For (INT x = 1; x <= 5; X ++)
 
Myint [X-1] = X;
 
Console. writeline ("display data in array ");
 
For (INT I = 1; I <= 5; I ++)
 
Console. writeline ("the {0} element value is {1}", I, Myint [I-1]);
 
Console. writeline ("display the nature of the array ");
 
Console. writeline (Myint. isfixedsize); // whether the size is fixed
 
Console. writeline (Myint. isreadonly); // read-only or not
 
Console. writeline (Myint. issynchronized); // whether to perform asynchronous operations
 
Console. writeline (Myint. Length); // array Length
 
Console. writeline (Myint. longlength); // The length of the array
 
Console. writeline (Myint. Rank); // dimension of the array
 
Console. writeline (Myint. syncroot); // array object
 
The running diagram is as follows:
 

The index number of the array element starts from 0, and Myint [0] is the first element of the array, and the last element is Myint [ArraySize-1]. if the index number is greater than or equal to the length of the array, an error occurs:
 

II. C # methods provided by Arrays
 
1. Common Instance Object Methods

Console. writeline (array. indexof (Myint, 3 ));

// Obtain the index number of element 3 in the array

Console. writeline (array. lastindexof (Myint, 3 ));

// Obtain the index number of element 3 in the array, and match the last element 3 in the array.

Console. writeline (array. asreadonly (Myint ));//

Array. Reverse (Myint); // returns the elements of the array.

For (INT I = 1; I <= 5; I ++)

Console. writeline ("the {0} element value is {1}", I, Myint [I-1]);
 

 

Console. writeline (Myint. getlength (0); // gets the number of elements of the specified dimension.
 
Console. writeline (Myint. getlonglength (0 ));
 
Console. writeline (Myint. getlowerbound (0); // obtain the lower limit of the specified dimension;
 
Console. writeline (Myint. GetType (); // type of the current instance object
 
Console. writeline (Myint. getvalue (2); // obtain the value of an element whose quotation marks are 2 in the array.
 
Console. writeline (Myint. gethashcode (); // obtain the object hash?
 
Console. writeline (Myint. tostring ());
 
Console. writeline (Myint. getenumerator (); // obtain the object Enumeration
 
Myint. setvalue (111,0); // set {newvalue, index_of_array
 
Console. writeline (Myint [0]);
 
Console. writeline ("clone method ");
 
Int [] orignalarray = {1, 2, 3 };
 
Int [] clonearray = (INT []) orignalarray. Clone (); // clone a new identical Array
 
Clonearray [0] = 10;
 
Clonearray [1] = 20;
 
Clonearray [2] = 30;
 
Foreach (int I in orignalarray)
 
Console. writeline (I );
 
Foreach (int I in clonearray)
 
Console. writeline (I );
 
Int [] copyarr = new int [Myint. Length];
 
Myint. copyto (copyarr, 0); // copy an array to another Array
 
Console. writeline ("{0}, {1}, {2}, {3}, {4}", copyarr [0], copyarr [1], copyarr [2], copyarr [3], copyarr [4]);
 
Console. writeline ("{0}, {1}, {2}, {3}, {4}", Myint [0], Myint [1], Myint [2], myint [3], Myint [4]);
 
Int [] array_1 = new int [5];
 
For (INT I = array_1.getlowerbound (0); I <= array_1.getupperbound (0); I ++)
 
Array_1 [I] = I + 1; // obtain the lower limit of the specified dimension to obtain the upper limit of the specified dimension.
 
For (Int J = array_1.getlowerbound (0); j <= array_1.getupperbound (0); j ++)
 
Console. writeline ("array_1 [{0}] = {1}", J, array_1 [J]);

 

// This program implements strates various ways
// Create and manipulate array types.
//
// Comment/uncomment method callin main ()
// To test.

Using system;
Using system. Collections. Generic;
Using system. text;

Namespace funwitharrays
{
Class Program
{
Static void main (string [] ARGs)
{
Console. writeline ("****** fun with arrays *****");
Simplearrays ();
Arrayinitialization ();
Arrayofobjects ();
Rectmultidimensionalarray ();
Jargedmultidimensionalarray ();
Passandreceivearrays ();
Systemarrayfunctionality ();
Console. Readline ();
}

# Region helper Methods
Static void simplearrays ()
{
Console. writeline ("=> simple array creation .");
// Create and fill an array of 3 Integers
Int [] myints = new int [3];
Myints [0] = 100;
Myints [1] = 200;
Myints [2] = 300;

// Now print each value.
Foreach (int I in myints)
Console. writeline (I );
Console. writeline ();
}

Static void arrayinitialization ()
{
Console. writeline ("=> array initialization .");
// Array initialization syntax using the new keyword.
String [] stringarray = new string [] {"one", "two", "three "};
Console. writeline ("stringarray has {0} elements", stringarray. Length );

// Array initialization syntax without using the new keyword.
Bool [] boolarray = {false, false, true };
Console. writeline ("boolarray has {0} elements", boolarray. Length );

// Array initialization with New Keyword and size.
Int [] intarray = new int [4] {20, 22, 23, 0 };
Console. writeline ("intarray has {0} elements", intarray. Length );
Console. writeline ();
}

Static void arrayofobjects ()
{
Console. writeline ("=> array of objects .");

// An array of objects can be anything at all.
Object [] myobjects = new object [4];
Myobjects [0] = 10;
Myobjects [1] = false;
Myobjects [2] = new datetime (1969, 3, 24 );
Myobjects [3] = "Form & void ";

Foreach (Object OBJ in myobjects)
{
// Print the type and value for each item in array.
Console. writeline ("type: {0}, value: {1}", obj. GetType (), OBJ );
}
Console. writeline ();
}
Static void rectmultidimensionalarray ()
{
Console. writeline ("=> rectangular multidimensional array .");
// A rectangular MD array.
Int [,] mymatrix;
Mymatrix = new int [6, 6];

// Populate (6*6) array.
For (INT I = 0; I <6; I ++)
For (Int J = 0; j <6; j ++)
Mymatrix [I, j] = I * J;

// Print (6*6) array.
For (INT I = 0; I <6; I ++)
{
For (Int J = 0; j <6; j ++)
Console. Write (mymatrix [I, j] + "\ t ");
Console. writeline ();
}
Console. writeline ();
}

Static void jagedmultidimensionalarray ()
{
// Multi-dimensional array
Console. writeline ("=> maid array .");
// A jagged MD array (I. e., an array of arrays ).
// Here we have an array of 5 different arrays.
Int [] [] myjagarray = new int [5] [];

// Create the jarged array.
For (INT I = 0; I <myjaarray. length; I ++)
Myjaarray [I] = new int [I + 7];

// Print each row (Remember, each element is defaulted to zero !)
For (INT I = 0; I <5; I ++)
{
For (Int J = 0; j <myjaarray [I]. length; j ++)
Console. Write (myjaarray [I] [J] + "");
Console. writeline ();
}
Console. writeline ();
}

Static void printarray (INT [] myints)
{
For (INT I = 0; I <myints. length; I ++)
Console. writeline ("item {0} is {1}", I, myints [I]);
}

Static string [] getstringarray ()
{
String [] thestrings = {"hello", "from", "getstringarray "};
Return thestrings;
}

Static void passandreceivearrays ()
{
Console. writeline ("=> arrays as Params and return values .");
Int [] ages = {20, 22, 23, 0 };
Printarray (AGEs );
String [] STRs = getstringarray ();
Foreach (string s in STRs)
Console. writeline (s );
Console. writeline ();
}

Static void systemarrayfunctionality ()
{
Console. writeline ("=> working with system. array .");
// Initialize items at startup.
String [] gothicbands = {"tones on tail", "Bauhaus", "Sisters of Mercy "};

// Print out names in declared order.
Console. writeline ("-> here is the array :");
// Getupperbound
For (INT I = 0; I <= gothicbands. getupperbound (0); I ++)
{
// Print a name
Console. Write (gothicbands [I] + "");
}
Console. writeline ("\ n ");

// Reverse them...
// Reverse the Array
Array. Reverse (gothicbands );
Console. writeline ("-> the reversed array ");
//... And print them.
For (INT I = 0; I <= gothicbands. getupperbound (0); I ++)
{
// Print a name
Console. Write (gothicbands [I] + "");
}
Console. writeline ("\ n ");

// Clear out all but the final member.
Console. writeline ("-> cleared out all but one ...");
Array. Clear (gothicbands, 1, 2 );
For (INT I = 0; I <= gothicbands. getupperbound (0); I ++)
{
// Print a name
Console. Write (gothicbands [I] + "");
}
Console. writeline ();
}
# Endregion
}
}

 

 

Ii. arraylist
 
Array is a static array. Once the array size is determined during initialization, it cannot be modified or the elements in the array cannot be added or deleted. this is not very flexible. Therefore, C # provides arraylist to process dynamic arrays .,
 
After creating arraylist, you can add and delete elements as needed. This is very useful. Let's take a look at the arraylist constructor.
 
Arraylist Al = new arraylist ();
 
Let's look at a simple example:
 
Arraylist Al = new arraylist ();
 
Console. writeline
 
("Initial number of elements:" + Al. Count );
 
Console. writeline ("adding 6 elements ");
 
// Add elements to the array list
 
Al. Add ('C ');
 
Al. Add ('A ');
 
Al. Add ('E ');
 
Al. Add ('B ');
 
Al. Add ('D ');
 
Al. Add ('F ');

 

Al. Remove ('A'); // deletes an element.

Console. writeline (Al. Count );

Al. Add ('A'); // Add an element.

Console. writeline (Al. Count );

Al [0] = 'X'; // modify the array element

Al [1] = 'y ';

Al [2] = 'Z ';
 

// After deleting an element, the number changes to 5, and the number of elements after adding one is 6.

Now let's create an arraylist of numbers to learn its method;
 
Arraylist Al = new arraylist ();
 
// Add elements to the array list
 
Al. Add (155); Al. Add (413 );
 
Al. Add (-41); Al. Add (818 );
 
Al. Add (31); Al. Add (191 );
 
Console. Write ("original contents :");
 
Foreach (int I in Al)
 
Console. Write (I + "");
 
Console. writeline ("\ n ");
 
// Sort
 
Al. Sort ();
 
Console. Write ("contents after sorting :");
 
Foreach (int I in Al)
 
Console. Write (I + "");
 
Console. writeline ("\ n ");
 
Console. writeline ("index of 413 is" +
 
Al. Binary Search (413 ));
 

1. Learning arraylist related methods
 
Use enumerator to access the array:
 
Arraylist list = new arraylist (1 );
 
For (INT I = 0; I <10; I ++)
 
List. Add (I );
 
Ienumerator ETR = List. getenumerator (); // Enumeration
 
While (ETR. movenext ())
 
Console. Write (ETR. Current + "");
 
Running result:
 

By the way, to use arraylist in C #, you must add a reference to the system namespace. Otherwise, an error occurs. Using system. collections;
 
The following describes some common methods for Dynamic Arrays:
 
Arraylist list = new arraylist (5 );
 
// Construct a dynamic array
 
// List. Clear (); // clear all elements in the array
 
Console. writeline ();
 
Console. writeline ("there are {0} elements in the list", list. Count );
 
Arraylist shuzu = new arraylist (5 );
 
Shuzu. Add ("xianjian 1 ");
 
Shuzu. Add ("Liang Jian ");
 
Shuzu. Add ("bianceng .");
 
Shuzu. Add ("National Treasure ");
 
Shuzu. Add ("Lu Xiaofeng ");
 
For (INT x = 0; x <= shuzu. Count-1; X ++)
 
Console. writeline (shuzu [x]);
 
Console. writeline ("Now reverse it \ n ");
 
Shuzu. Reverse ();
 
Console. writeline ("after reverser \ n ");
 
Console. writeline ();
 
For (INT x = 0; x <= shuzu. Count-1; X ++)
 
Console. writeline (shuzu [x]);
 
Running result:
 

Now compare array and arraylist: array provides some flexibility that arraylist does not have. For example:
You can set the lower limit of array, but the lower limit of arraylist is always zero.
Array can have multiple dimensions, while arraylist is always only one-dimensional. array of a specific type (excluding objects) has better performance than arraylist because the elements of arraylist belong to the object type, therefore, packing and unboxing are often generated when the storage or retrieval value type is used.
 
Array is in the system namespace; arraylist is in the system. Collections namespace
 
As for the parent class methods inherited from the object class in arraylist, I will not introduce them here,
 
These are some basic methods. The following describes how to use arraylist.
 

 

Console. writeline ();

For (INT x = 0; x <= shuzu. Count-1; X ++)

Console. writeline (shuzu [x]);

Console. writeline ("there are {0} elements in the list", shuzu. Count );

Console. writeline ("now add a new elements ");

Shuzu. Add ("new element"); // Add an element.

Console. writeline ("there are {0} elements in the list", shuzu. Count );

Shuzu. Remove (""); // deletes a feature element.

Console. writeline ("there are {0} elements in the list", shuzu. Count );

Shuzu. removeat (2); // deletes the element at the specified position.

Console. writeline ("there are {0} elements in the list", shuzu. Count );

Shuzu. insert (1, "system level"); // insert an element at the specified position of the array

Console. writeline ("there are {0} elements in the list", shuzu. Count );

Int countelement = shuzu. count;

Console. writeline (shuzu. GetType (); // type of the output Array

Int Index = shuzu. indexof ("system level"); // gets the index number of an element.

Console. writeline ();

Arraylist anothe = new arraylist (shuzu); // create an array

For (INT B = 0; B <anothe. Count; B ++)

Console. writeline (anothe [B]);

Console. writeline (shuzu. Contains ("National Treasure"); // determines whether an element exists in the array.

Console. writeline (shuzu. lastindexof ("National Treasure "));
 

List. Add ("B ");

List. Add ("G ");

List. Add ("J ");

List. Add ("S ");

List. Add ("M ");

String [] array1 = new string [list. Count];

// Create a string array with the same size as the number of shuzu Elements

List. copyto (array1, 0 );

// Copy the elements starting from the first element in shuzu to the array

Object [] array2 = List. toarray (); // use this method to create an array

Console. writeline ("array 1 :");

Foreach (string s in array2)

{

Console. Write ("{0}", S );

}

Console. writeline ();

Foreach (string s in array1)

{

Console. Write ("{0}", S );

}

Console. writeline ();

For (INT I = 0; I <list. Count; I ++)

Console. Write (list [I]);
 

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.