C # Fundamentals-Arrays and collections

Source: Internet
Author: User

I. Arrays and collections
Arrays: can store any number of data of the same type

Data item: Same type

① Each data type has a number (index or subscript)

The index of the ② data (subscript) is a number of type int

③ starts at 0 and sequentially numbers each of the array items in the data

Declaration and assignment of an array

Declaration: data type [] variable name;

Assignment: variable name [index] = value;

Reads the length variable name of the array. Length return type int

Merge writing: data type [] Variable name = new data type [length];
(Array declaration and assignment, data type reading and modification, reading the length of the array)

The default value of an array item: After an array is created, its value for each array item is the default value for the group item type.

Common default values: String Type default value is Mull (indicates no data)

Example

Create a string array of length 3, and then assign a, B, C, and finally, the length of the array to each of its items.

Merge writing

Strs[0] = "a";
STRS[2] = "C"; Sring[] STRs = {"A", "B", "C"};
Console.Write (STRs. Length); Console.Write (STRs. Length);


Numbers[0] = 3;
NUMBERS[2] = numbers[0] * 2 + numbers[1];
Console.WriteLine (Numbers. Length); Console output 4,5

Second, the fixed staying power of the array

Once an array is created, its length is constant

nums = new int [6]; Re-create an array of length 5 by using the previous array no longer

Arrays are suitable for scenarios where the number of data is fixed

Scenario for working with arrays: Save all prime numbers within 100
Preserving the mass of all known planets in the solar system
Save all card data in standard poker
Save all dates for one weeks
Other fixed-length data scenarios

Not suitable for use with arrays: Save a class student's information
Save all dates in a year
Save a player's hand data in a bucket landlord game
Save equipment information for a game player
Other indeterminate data scenarios

Three, the traversal of the array

Repeating behavior: outputting an array item

Code writing Format:Console.WriteLine (arrays [?]); which As an index

int i =? ;
Variation range of variable I: 0~arrays,length-1 can also be written as: I < arrays. Length

Traverse

Definition: Refers to the beginning of the first item of an array, followed by the complete array of all items

The ① implements the traversal of the array, and can use loops

The ② loop variable starts at 0 and then takes the maximum subscript of the array (the length of the array-1)

③ in the loop body, the value of each item of the array can be removed by using the loop body variable as the subscript

{
}

Full implementation Code

Console.Write ("The length of the Pro input array:");int len =Int, Parse (Conesole,readline ());//Creates an array based on the user's input, and iterates through the array for each of its items assignedint[] Nums =0; I < Nums. Length; i++{Console,write ("Please enter the array"+ (i +1) +"The value of the item:"); Nums[i] =int. Parse (Console.ReadLine ());} // iterate through the array nums, and sequentially output the values in the array console.write (" all items of the array are:");  for (int i = 0; i < Nums. Length; i++) {Console.Write (nums[i]);  if (I < nums. Length- 1)// not the last item Console.Write (",");  output A comma-delimited                 

Iv. sort of exchange

Order by number of inputs: Simplify sorting: How to put the smallest number in the position of an array index not 0

Implementation method: The number of the first position is taken out and then compared to the number in the back position, if the number is larger than the trailing position, then the swap position

All code Implementation

For (1; i++) {for(1; j < numbers). Count; J +if (numbers [i]>numbers [j]) {int temp = Numbers[i];numbers[i] = numbers [j];numbers[j] =< c15> temp;          }}}

  

Five, Array analyzer

code example:

Console.Write ("Please enter the length of the array:");int n =Int. Parse (Console.ReadLine ());int[] Nums =NewInt[n]; {for (int i =0; I < Nums. Length; i++) {Console.Write ("Please enter an array of"+ (i +1) +"Item"); Nums[i] =Int. Parse (Console.ReadLine ());} Console.clear ();}for (int i =0; I < Nums. Length-1; i++){for (Int J = i +1; J < Nums. Length; J + +)if (nums[i) >Nums[j]) {int temp =Nums[i];nums[i] =NUMS[J];NUMS[J] =temp;}} Console.Write ("The sort of numbers you enter from small to large is:");for (int i =0; I < Nums. Length; i++) {Console.Write (Nums[i] +"");} Console.ReadLine (); {Console.Write ("The number that you enter is odd:");for (int i =0; I < Nums. Length; i++)If (Nums[i]%2! =0) {{Console.Write (Nums[i] +"");}} Console.ReadLine ();} Console.Write ("The numbers you enter are prime numbers:");for (int i =0; I < Nums. Length; i++) {bool Isfind = false; For (int j = 2; j < Nums[i]; j + +) {if (nums[i]% J = 0) {isfind = true;  Break;}} if (isfind) {}else{console.write (nums[i] + " ");}} Console.ReadLine ();                  

Six, the collection

Data: Fixed length (used to hold a constant amount of data) less memory traversal speed

Set: Indefinite Length (the number of saved data, which can change continuously during the execution of a program) is slow in memory traversal

List Collection

Create: Definition:list< data type > variable name;

Assignment: Variable name = new list< data type > ();//set is indeterminate so the assignment is not specified length, the length can be changed after the assignment value

Initializer: variable name = new list< data type >{element 1, Element 2,, Element N,};

Operation

1. Add element: variable name. Add (the data to be added);

Nums. ADD (1);
Nums. ADD (3);

2. Insert element: Inserts a new element into the specified position of the collection

The variable name. Insert (index, the data to be inserted);

Nums. Insert (1,10);

3. Delete element: variable name. RemoveAT (index); Delete the element at the specified index location

The variable name. Remove (data);
Deletes the first occurrence in the collection that is the same as the filled data

Nums. RemoveAt (2);
Nums. Remove (1);

4. Modifying elements: Modifying one of the values in an element

Variable name [index] = value;

Code implementation

int maxindex = numbers. Count-1; Console.Write ("Please enter a subscript to delete (0-"+maxindex +")");int index = int. Parse (Console.ReadLine ()); if (Index < 0 | | index > maxindex) {Console.WriteLine (" Yes! You entered the wrong, subscript out of range, press ENTER to continue "); Console.ReadLine ();} Else{Console.WriteLine (" please re-enter a new number ");  int newnum = int. Parse (Console.ReadLine ()); Numbers[index] = newnum;}           


5. Get the number of elements: the length variable name of the collection. Count

Summary: In the function, the array can be implemented by all the functions of the set can be implemented conversely, the collection can achieve some functions, data difficult to implement (data, collection, List collection)

collection types for C #

}

For loop reality: low efficiency

{
}

Comparison of foreach and for

foreach: For traversal only, cannot change loop target, fast traverse speed, high execution efficiency
For: can be used in any form of repetitive behavior, in cyclic weight, can do any operation, slow traverse, low execution efficiency

If you need to traverse and combine, and the traversal only needs to read without changing, using the Foreach loop is most appropriate, and vice versa, select other loops as needed (foreach, for)

C # Fundamentals-Arrays and collections

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.