A deep understanding of the use of foreach traversal in C #

Source: Internet
Author: User
Iterating through a list in C # is a common way to use it, and the following article introduces you to the use of foreach traversal in C #, followed by some examples of how C # uses foreach, which is described in detail in the sample code, For everyone has a certain reference learning value, the need for friends to see together below.

Objective

This article mainly introduces the use of foreach traversal in C # and some things that C # needs to know about using foreach, to share it for your reference, and to take a look at the detailed introduction:

I. foreach traversal usage in C #

The Foreach loop is used to enumerate all the elements in the collection, and the expressions in the foreach statement consist of two items separated by the keyword in. The item on the right is the collection name, and the item on the left is the variable name that holds each element in the collection.

The loop runs as follows: Each time a loop is taken, a new element value is fetched from the collection. In a read-only variable, if the entire expression in parentheses returns a value of True,foreach block, the statement can be executed. Once the elements in the collection have been accessed, the value of the entire expression is false, and the control flow is transferred to the execution statement following the foreach block.

The foreach statement is often used with arrays, and the following instance reads the values of the array and displays them through a foreach statement.

Properties of the array: the capacity of the Array.Length array

Using this property, we can get the capacity value that the array object allows to store, that is, the length of the array, the number of elements, this is better understood, the array has other properties, such as the number of dimensions of the array, the use of the property is relatively simple, learn one, the other format is basically the same, here we do not example.

When the array has more dimensions and more capacity, C # provides a foreach statement that is designed to read all the elements in the collection/array, and we call this function traversal. The syntax is written as follows:

Traversing arrays: foreach (Type objname in Collection/array)

This statement examines the values of the variables stored in the array one at a time, and takes them all out, where the type is the data type that the array object you are reading is going to be stored in the objname variable, and objname is the variable name that defines a type. Represents each element taken from the collection and Array (Collection/array), and Collection/array is the object to be accessed. In this way, you can simply write a foreach to iterate through an array of all the dimensions except the jagged array.

Note: The data type of objname must be the same as or larger than the type of the Collection/array object.

Let's take an example of using a foreach and for traversal rule array, which involves an array of methods to get the dimension, and compare the advantages of foreach on a one-time traversal of the rule array.


int[,] A = new int[2, 2, 2] {{{1, 2}, {3,4}},{{5, 6}, {7,8}}};//define a 2-dimensional array afor (int i = 2; i < A.getlen) in 2 rows 3 columns 0;  Gth (0); i++)//Use Array.getlength (n) to get the number of elements on the array [0,1,,, N], 0 for rows, 1 columns, and n for this array is n+1 dimension {for (int j = 0; J < a.getlength (1); {for (int z = 0; z < a.getlength (2); z++)//2 represents the number of elements in depth, and if the array has n dimensions it has to write N for loop {Console.WriteLine (a[i,j,z]);}}

Iterating through a array at once with a foreach loop


int[,] A = new int[2, 2, 2] {{{1, 2}, {3,4}},{{5, 6}, {7,8}}};//a 2-dimensional array aforeach (int i in a) {Console, 2 rows 2 columns 3 depth. WriteLine (i);}

The result of both code execution is the same as one element per line, a total of 8 rows, the elements are 1 2 3 4 5 6 7 8

Let's take another example, an example of accessing an array element using a for and a foreach loop, first prompting the user to enter the number of students, and then using the number of students as the number of elements in the array names to store the student's name, with a for loop starting at 0 bits from the index I of the array. Enter the student name "prompt, and the user entered the name of the student according to its index in the array names[i] stored in the names array, the maximum for the number of cycles (that is, the maximum value of the index) through the array properties .Length , we said that the relationship between the capacity and index is index=Array.Length-1 , The maximum value of I

It is important to note that with foreach, only one by one of the elements in the array can be obtained, and this statement cannot be used to alter the elements stored in the array.



Using system;class program{static void Main () {int count; Console.WriteLine ("Enter the number of students to be enrolled"); count = Int. Parse (Console.ReadLine ()); String[]names = new String[count]; for (int i = 0; i < names. Length; i++) {Console.WriteLine ("Please enter the name of the student {0}", i + 1); Names[i] = Console.ReadLine ();} Console.WriteLine ("Registered students as follows"); foreach (string name in Names) {Console.WriteLine ("{0}", name);} Console.readkey (); }}

Second, C # uses the foreach need to know

Traversing a list through foreach in C # is a frequently used method, convenient to use, and not as much of a difference in performance as for a for; why pay attention? Let's take a look at the following sentence: there is a direct relationship between the amount of memory allocated and the time it takes to complete the test. Memory allocations are not very expensive when we look at them separately. However, when the memory system only occasionally cleans up unused memory, the problem arises, and the frequency of the problem is proportional to the amount of memory to allocate. As a result, the more memory you allocate, the more frequently the memory is garbage collected, and the worse your code performance becomes.

From the above words you can see that the memory recycling is very lossy resources, then we look at some of the. NET internal types of implementation.

Array:


System.arraypublic IEnumerator GetEnumerator () {int lowerbound = this. Getlowerbound (0); Rank = = 1 && lowerbound = = 0) {return new array.szarrayenumerator (this);} return new Array.arrayenumerator (this, lowerbound, this. Length);}

List<t>:


System.collections.generic.list<t>public List<t>. Enumerator GetEnumerator () {return new List<t>. Enumerator (this);}

Dictionary<tkey, Tvalue>:


System.collections.generic.dictionary<tkey, Tvalue>public Dictionary<tkey, TValue> Enumerator GetEnumerator () {return new Dictionary<tkey, Tvalue>. Enumerator (this, 2);}

Judging from the code above, we will build a enumerator when we do the above objects with foreach, and maybe some people will think that this thing is not necessary, but there are many cases do not care; But if the results from memory analysis show that the number of building enumerator is ranked in the first few, then really care about it. A very simple application assumes that your application handles several watts of concurrency, and that each time there are several foreach, you can calculate how many objects are generated and recycled?

Looking at a simple analysis, there is a list ' 1 tightly, what happens if there are more than one foreach inside the component?

What about the result of the change to for?


summary

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.