Home  >  Article  >  Backend Development  >  In-depth understanding of the use of foreach traversal in C#

In-depth understanding of the use of foreach traversal in C#

黄舟
黄舟Original
2017-08-08 10:50:483712browse

Traversing a list through foreach in C# is a frequently used method, and it is also convenient to use. The following article first introduces you to the use of foreach traversal in C#, and then introduces some things to pay attention to when using foreach in C#. Yes, the article introduces it in detail through sample code, which has certain reference and learning value for everyone. Friends who need it can take a look below.

Preface

This article mainly introduces to you the usage of foreach traversal in C# and some things you need to know when using foreach in C#. Share it. For your reference and study, there is not much to say below, let’s take a look at the detailed introduction:

1. Usage of foreach traversal in C

The #foreach loop is used to list all elements in the collection. The expression in the foreach statement consists of two items separated by the keyword in. The item on the right side of in is the collection name, and the item on the left side of in is the variable name, which is used to store each element in the collection.

The operation process of this loop is as follows: each time it loops, a new element value is taken out from the set. Put it in a read-only variable. If the entire expression in the brackets returns true, the statement in the foreach block can be executed. Once all elements in the collection have been accessed and the entire expression evaluates to false, control flows to the execution statement following the foreach block.

The foreach statement is often used with arrays. The following example will read the value of the array through the foreach statement and display it.

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

Using this property, we can obtain the capacity value that the array object is allowed to store, and also It is the length and number of elements of the array. This is easier to understand. Arrays also have other attributes, such as the dimensions of the array. The usage of attributes is relatively simple. Once you learn one, the other formats are basically the same. We will not give examples here. .

When the array has many dimensions and capacity, C# provides the foreach statement, which is specially used to read all elements in the collection/array. We call this function traversal. The syntax is written as follows:

Traverse the array: foreach (type objName in collection/Array)

This statement will check all the items in the array one by one Stored variable values, and take them out one by one, where type is the data type of the array object you want to read that will be stored in the objName variable, and objName is a variable name that defines a type type, representing each time from the collection and The elements obtained from the array (collection/Array), collection/Array is the array object to be accessed. In this way, you only need to write a foreach to traverse arrays of all dimensions except jagged arrays.

Note: The data type type of objName must be the same as or larger than the type of the collection/Array object.

Below we give an example of using foreach and for to traverse a rule array, which involves a method of obtaining the dimensions of an array, and compares the advantages of foreach in traversing the rule array at once.


int[,,] a = new int[2, 2, 2] { {{ 1, 2 }, { 3,4}},{{ 5, 6 }, { 7,8}} };// 定义一个2行2列2纵深的3维数组a
for (int i = 0; i < a.GetLength (0) ;i++ ) //用Array.GetLength(n)得到数组[0,1,,,n]上的维数的元素数,0代表行,1列,n代表此数组是n+1维
{
 for (int j = 0; j < a.GetLength(1); j++)
 {
 for (int z = 0; z < a.GetLength(2);z++ )//2代表得到纵深上的元素数,如果数组有n维就得写n个for循环
 {
 Console.WriteLine(a[i,j,z]);
 }
 }
}

Use a foreach loop to traverse an array at once


int[,,] a = new int[2, 2, 2] { {{ 1, 2 }, { 3,4}},{{ 5, 6 }, { 7,8}} };//定义一个2行2列2纵深的3维数组a
foreach(int i in a)
{
 Console .WriteLine (i);
}

These two codes The execution result is the same, each line has one element, a total of 8 lines, the elements are 1 2 3 4 5 6 7 8

Let’s make another example, which is using for and foreach An example of looping to access array elements. First, the user is prompted to enter the number of students, and then the number of students is used as the number of elements in the array names that stores the students' names. A for loop is used to loop the output starting from the 0 position according to the index i of the array. "Enter student name" prompt, and store the student name entered by the user in the names array according to its index in the array names[i], the maximum value of the number of for loops (that is, the maximum value of the index ) is obtained through the array attribute .Length. We have said that the relationship between capacity and index is index=Array.Length-1. This question is the maximum value of i

It must be noted that: With the help of foreach, you can only obtain the elements in the array one by one, and you cannot use this statement to change the elements stored in the array.



##

using System;
class Program
{
 static void Main()
 {
 int count;
 Console.WriteLine("输入要登记的学生数");
 count = int.Parse(Console.ReadLine());
 string[]names = new string[count];
 for (int i = 0; i < names.Length; i++)
 {
 Console.WriteLine("请输入第{0}个学生的姓名", i + 1);
 names[i] = Console.ReadLine();
 }
 Console.WriteLine("已登记的学生如下");
 foreach (string name in names)
 {
 Console.WriteLine("{0}", name);
 }
 Console.ReadKey();
 }
}

2. What you need to know when using foreach in C

# Traversing a list through foreach is a frequently used method in C#. It is easy to use and there is not much difference in performance from for; so why should you pay attention? Let's first look at the following sentence: There is a direct relationship between the amount of memory allocated and the time required to complete the test. When we look at it alone, memory allocation is not very expensive. However, problems arise when the memory system only occasionally cleans up unused memory, and the frequency of the problem is proportional to the amount of memory to be allocated. Therefore, the more memory you allocate, the more frequently the memory will be garbage collected, and the worse your code's performance will become.

从上面那些话可以看到内存的回收是非常损耗资源,那我们再看下一些.net内部类型的实现。

Array:


// System.Array

public IEnumerator GetEnumerator()

{

int lowerBound = this.GetLowerBound(0);

if (this.Rank == 1 && lowerBound == 0)

{

return new Array.SZArrayEnumerator(this);

}

return new Array.ArrayEnumerator(this, lowerBound, this.Length);

}

List8742468051c85b06f0a0af9e3e506b5c:


// System.Collections.Generic.List<T>

public List<T>.Enumerator GetEnumerator()

{

return new List<T>.Enumerator(this);

}

Dictionaryb6842da76bed01162354d37c4f2d3464:


// System.Collections.Generic.Dictionary<TKey, TValue>

public Dictionary<TKey, TValue>.Enumerator GetEnumerator()

{

return new Dictionary<TKey, TValue>.Enumerator(this, 2);

}

从以上代码来看,我们再进行foreach操作以上对象的时候都会构建一个Enumerator;也许有人会认为这点东西不需要计较,不过的确很多情况是不用关心;但如果通过内存分析到到的结果表明构建Enumerator的数量排在前几位,那就真的要关心一下了。很简单的一个应用假设你的应用要处理几W的并发,而每次都存在几次foreach那你就能计算出有多少对象的产生和回收?

看下一个简单的分析图,这里紧紧是存在一个List'1如果组件内部每个并发多几个foreach又会怎样?

改成for的结果又怎样呢


总结

The above is the detailed content of In-depth understanding of the use of foreach traversal in C#. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn