c#&& Array

Source: Internet
Author: User

Arrays are the most common data structures that appear in almost all programming languages. The use of arrays in C # requires the creation of an object of type System.Array, which is the abstract base class for all arrays.
The array class provides a set of methods for sorting and finding
Another alternative to creating an array is that arraylist,arraylist is an array that can grow dynamically as needed.
ArrayList is a good choice when it is not possible to determine the size of an array, or when the array needs to be changed in the lifetime of the program.
There are also copies, cloned content, comparison equality, and static methods with array and ArrayList.

Declaring and first-order arrays
The array declaration is in the following format:

Type[] Array_Name;
The type is the datatype, such as
String[] names;

The second line needs to instantiate the array (because it is a System.Array type) and specify the size of the array. The code is as follows:
names = new STRING[10];
This allocates memory for 10 strings.

You can also write two sentences together:

string[] names = new STRING[10];
Sometimes you want to make a declaration, instantiate, and specify the data in three steps at the same time, that's what it looks like:
int[] numbers = new int[] {1,2,3,4,5};
This string of numbers, called the initial list, is enclosed in curly braces, with each element separated by commas.
When declaring an array this way, the compiler will automatically specify the number of first-order lists without specifying the array size.

Setting and accessing array elements
The storage of an array element can be stored either directly or by calling the SetValue method, and the direct storage method needs to specify the position within the array with the index, as follows:

NAMES[2] = "Raymond";
SALES[19] = 23123;
The SetValue method provides a more object-oriented approach to setting the value of an array element, which has two parameters, one is the number of indexes, and the other is a value.
Names. Setvalue[2, "Raymond"];
Sales. Setvalue[19, 23123];
The array element can be fetched either directly or by calling the GetValue method, GetValue with a simple parameter: index number

MyName = names[2];
Monthsales = sales. GETVALUE[19];

It is common to get each element in the array by looping through it. Programmers often make a mistake when writing loops: they write the upper limit of the loop or call the method that gets the upper limit.
The error is mainly because the upper bound of the array is dynamic
for (int i = 0; I <= sales. GetUpperBound (0); i++)
TotalSales = TotalSales + sales[i];
Methods and properties for retrieving array metadata:
Length: Returns all the number of array elements.
GetLength: Returns the number of elements in one dimension of an array element.
Rank: Returns the number of dimensions
GetType: Returns the type of the current array instance

The length method is useful when counting the number of elements in a multidimensional array. Otherwise, use the GetUpperBound method +1 to take this value
because the length method returns the number of elements in the array, the GetLength method returns the number of arrays in one dimension.
The Rank property can change the size of the array at run time without worrying about losing data, which is discussed in detail later in the chapter.
The GetType method is the method used to determine the data type when you are not sure of the array type, such as the array is the entry parameter.
The following code creates a variable of type types that allows us to invoke a class method: IsArray () to determine whether the object is an array,
if it is an array, then the data type of the array is returned .
int[] numbers;
numbers = new int[] {0,1,2,3,4};
Type arraytype = numbers. GetType ();
if (Arraytype.isarray)
Console.WriteLine ("The array type is: {0}", arraytype);
Else
Console.WriteLine ("Not an array");
Console.read ();

The GetType method not only returns the type of the array, but also tells us that the array is actually an object, and the following is the output code:
The array type is:system.int32[]
The square brackets indicate that this object is a group, and also note the format we use when displaying the array type.
Knowing this, we can't convert this type into a string to concatenate the rest of the string

Multidimensional arrays
At present, our discussion is limited to one-dimensional arrays, C #, can use up to 32-dimensional arrays, although 3-dimensional arrays are not used (and chaotic).
A multidimensional array is declared with an array that specifies the upper bound of each dimension, with a 2-dimensional declaration:
Int[,] grades = new int[4,5];
Declares an array of 4 rows and 5 columns, and a 2-dimensional array is typically used to emulate matrices.
You can also declare a multidimensional array that does not specify the upper bound of each dimension, separated by commas.
As an example:
double[,] Sales;
Declares a 2-D array,
Double[,,] sales;
Declares a 3-dimensional array that, when you declare an array that does not specify the upper bound of a dimension, specifies

Multidimensional arrays can also be used in the first-order list, see the following code:
Int[,] grades = new int[,] {{1, 82, 74, 89, 100},
{2, 93, 96, 85, 86},
{3, 83, 72, 95, 89},
{4, 91, 98, 79, 88}}
First, notice that the upper bound of the array is not specified, and when an array is initially initialized with the initial list, the
The upper bound of the array cannot be specified. The compiler calculates the upper bound of each dimension through the initial list.
The initial list itself is a pair of curly braces, each of which is separated by commas.

The elements of the majority group are similar to one dimension, as is the case with traditional techniques:

Grade = grades[2,2];
grades[2,2] = 99
Or you can use the GetValue method
Grade = grades.getvalue[0,2];

However, you cannot use the SetValue method to set the data for a multidimensional array, because this method has only two parameters.

It is common to calculate all elements in a multidimensional array, although it is often based on data from a row or column.
With grades this array, if each row of the array is a student record, we can calculate the average score for each student in the grade:

(Code below)

int[,] grades = new int[,] {{1, * *
{2, ------
{3, a.
{4, 98 ,----);
int last_grade = grades. GetUpperBound (1);
double average = 0.0;
int total;
int last_student = grades. GetUpperBound (0);
for (int row = 0; row <= last_student; row++) {
Total = 0;
for (int col = 0; col <= last_grade; col++)
Total + = Grades[row, col];
average = Total/last_grade;
Console.WriteLine ("Average:" + Average);
}
}

Parameter array
Many of the methods are defined to provide several parameters, but there are times when you want to write an optional method of the number of arguments.
You can declare an array of arguments. The parameter array is defined with the keyword ParamArray to define the parameter list.
The following method allows any number of arguments, the return value is the number of parameters. static int sumnums (params int[] nums) {
int sum = 0;
for (int i = 0; I <= nums. GetUpperBound (0); i++)
Sum + = Nums[i];
return sum;
}

This method can be called by the following code:

Total = Sumnums (1, 2, 3);
Total = Sumnums (1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
When you define a method with a parameter array, the parameter array must be placed at the end of all parameters in this method,
This allows the compiler to handle the parameters correctly, otherwise the compiler does not know when the number of arguments will end.

Irregular arrays
When you create a multidimensional array, you always create a structure with the same number of elements in each row. For example, look at the following code:

int sales[,] = new int[12,30];//salesperson per month daily situation
Suppose each row (month) has the same number of elements (in days), and actually some 31 days, some 30 days, and some 29.
So the data has a vacant position, in this array the problem is not big, but once the data volume is large, it is wasted

The problem is solved by using an irregular array instead of a two-dimensional array.
An irregular array is an array of every row of an array as well as an array. Each dimension of an irregular array is a one-dimensional array, which is called "irregular" because the number of rows is different.
An irregular array may not look like a rectangle, but it has an irregular edge.
The irregular array is declared with two parentheses after the array name. The first pair of parentheses specifies the number of rows, and the second pair is left blank.
Int[][] jagged = new int[12][];

The code looks a bit strange, but it's clear to understand it separately. This irregular array has 12 elements.
Each element is also an array. The first order of the list is to first make each row of data, indicating that each row element is a data with 12 elements, each element is initially made the default value.
Once an irregular array is declared, the elements of each row can be specified, and the following code is the set value:
Jagged[0][0] = 23;
JAGGED[0][1] = 13;
. . .
JAGGED[7][5] = 45;
The first pair of parentheses indicates the line number, and the second pair of parentheses indicates an element of the line.
The first sentence takes the first element of the first line, and the second sentence takes the second element of the first line.
The third sentence takes the 8th element of line 6th.

An example of an irregular array, the following program creates an array called sales, which is used to calculate the average weekly sales for the two months.

using System;
class Class1 {
static void main[] {
int[] Jan = new int[31];
int[] Feb = new int[29];
int[][] Sales = new Int{jan, Feb};
int month, day, total;
double average = 0.0;
sales[0][0] = all;
sales[0][1] =;
sales[0][0] = all;
sales[0][1] =;
sales[0][2] =;
sales[0][3] = over;
sales[0][4] =;
sales[0][5] =;
sales[0][6] =;
sales[1][0] =;
sales[1][1] = Panax Notoginseng;
sales[1][2] = +;
sales[1][3] = +;
sales[1][4] =;
sales[1][5] =;
sales[1][6] =;
For (month = 0; month <= 1; month++) {
Total = 0;
For (day = 0; day <= 6; day++)
Total + = Sales[month][day];
average = TOTAL/7;
Console.WriteLine ("Average Sales for Month:" +
month + ":" + average);
}
}
}

ArrayList class
Static arrays are not so useful when you do not know the size of the array or if the size of the array is to be changed at run time.
One solution is to use an array type that is self-growing when there is not enough space, and this array is ArrayList, which is also part of the System.Collections.
The object of the ArrayList class has a capacity property to store the array size, the first value is 16, and when the element of the array is close to 16, capacity adds 16,
And of course the array space is also getting bigger. This is the case with ArrayList: the array may become larger or smaller, and it is more efficient than using ReDim in a standard array.
This first chapter also says that ArrayList stores object types, and if you need a strongly typed array, you should use a standard array or other data structure.

Here are some common methods or properties:
Add (): Adds an element to a ArrayList.
AddRange (): Adds a set of elements to ArrayList.
Capacity: storage ArrayList can hold the number of elements
Clear (): Removes an element from the ArrayList.
Contains (): Determines whether there is a specified element present in ArrayList.
CopyTo (): Copy ArrayList or part of ArrayList to an array class.
Count: Returns the number of elements within the ArrayList.
GetEnumerator (): Returns an iterator for the ArrayList.
GetRange (): Returns a subset of the ArrayList.
IndexOf (): Returns the index of the specified element for the first discovery.
Insert (): Inserts an element into the specified position of the ArrayList.
Insertrange (): Inserts a set of elements into the specified position of the ArrayList
Item (): Sets or gets the value at a specified location.
Remove (): Removes the specified element from the first discovery.
RemoveAt (): Removes the element from the specified position.
Reverse (): reverse order.
Sort (): alphabetical order.
ToArray (): Copies all elements to an array class.
TrimToSize (): Sets the capacity value to a value equal to the number of elements in the array.

Using the ArrayList class
ArrayList is not like a standard array. In general, add an element with Add (), unless you add it at a specific location, using Insert ().
Here, let's test the other ways to use ArrayList.
First declare an object ArrayList grades = new ArrayList ();
Note that the constructor is used here, and if ArrayList does not use a constructor, the ArrayList object cannot be used.
Add an element with the Add method, which has only one parameter, which is the object to be added to the ArrayList.
The Add method has a return value that returns the location of the insertion and is seldom used. Here is an example:
Grades. ADD (100);
Grades. ADD (84);
int position;
Position = grades. Add (77);
Console.WriteLine ("The Grade" is added at position:
"+ position);

The ArrayList object can be traversed with foreach, and ArrayList has a built-in enumerator
int total = 0;
Double average = 0.0;
foreach (Object grade in grades)
Total + = (int) grade;
Average = Total/grades. Count;
Console.WriteLine ("The average grade is:" + average);

If you want to add an element to a specific location, with the Insert method, there are two parameters, position and value
Grades. Insert (1, 99);
Grades. Insert (3, 80);

View ArrayList current capacity You can use the capacity property to see the number of arrays with the Count property
Console.WriteLine ("The current capacity of grades is:
"+ grades. capacity);
Console.WriteLine ("The number of grades in grades is:
"+ grades. Count);

Here are some other ways to remove elements, if you know the element you want to remove, but you don't know the location, with the Remove method, there is only one argument, which is the object you want to remove.
If the object exists in ArrayList, it is removed, otherwise, nothing is done. It's like the following code.
if (grades. Contains (54))
Grades. Remove (54)
Else
Console.Write ("Object not in ArrayList.");

If you know the location of the object to remove, using the RemoveAt method, this method has a parameter: The index of the object.
An exception occurs if an invalid index is passed in.
Grades. RemoveAt (2);

Get an index of an object using the IndexOf method, there is a parameter that is the object. Returns the index of this object. If not present, return-1
int POS;
pos = grades. IndexOf (70);
Grades. RemoveAt (POS);

If you want to add a collection of objects, this set of objects must derive from ICollection, meaning that this set of objects can exist in arrays, collection, or ArrayList.
Here are two different ways to add a set of objects to ArrayList. AddRange and Insertrange,addrange add elements to the end, and the Insertrange method is added to the specified location.

(Code below)

The results are as follows

The first two names at the beginning of the ArrayList are because the specified index is 0. The last ones are at the end because of the aaddrange.
There are also two common methods that are ToArray and GetRange methods. The GetRange method returns a set of objects in the ArrayList as a new ArrayList.
ToArray method copies all elements to an array element

The GetRange method has two parameters: the starting index and the number of elements to be obtained.
The GetRange method is not destructive, it just takes a copy. Here is an example code

ArrayList somenames = new ArrayList ();
Somenames = names. GetRange (2,4);
Console.WriteLine ("Somenames sub-arraylist:");
foreach (Object name in Somenames)
Console.WriteLine (name);

Summarize:

Arrays are the most commonly used data structures. Almost all programming languages have built-in array types.
In many applications, arrays are the simplest and most efficient data structures, and arrays are useful.
. NET has a new array type called ArrayList, which is basically the same as the group, but even stronger is that it can reset the capacity.
ArrayList also has some useful methods, such as inserting, deleting, and finding.
Because C # does not allow programmers to dynamically change the size of an array like vb.net, ArrayList is a useful data structure without knowing the size of the array.

c#&& Array

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.