Home Backend Development C#.Net Tutorial In-depth understanding of the use of foreach traversal in C#

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

Aug 08, 2017 am 10:50 AM
.net foreach

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]);
 }
 }
}
Copy after login

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);
}
Copy after login

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();
 }
}
Copy after login

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);

}
Copy after login

List:


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

public List<T>.Enumerator GetEnumerator()

{

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

}
Copy after login

Dictionary


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

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

{

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

}
Copy after login

从以上代码来看,我们再进行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 of this Website
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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

What is the difference between using foreach and iterator to delete elements when traversing Java ArrayList? What is the difference between using foreach and iterator to delete elements when traversing Java ArrayList? Apr 27, 2023 pm 03:40 PM

1. The difference between Iterator and foreach is the polymorphic difference (the bottom layer of foreach is Iterator) Iterator is an interface type, it does not care about the type of collection or array; both for and foreach need to know the type of collection first, even the type of elements in the collection; 1. Why is it said that the bottom layer of foreach is the code written by Iterator: Decompiled code: 2. The difference between remove in foreach and iterator. First, look at the Alibaba Java Development Manual, but no error will be reported in case 1, and an error will be reported in case 2 (java. util.ConcurrentModificationException) first

How to determine the number of foreach loop in php How to determine the number of foreach loop in php Jul 10, 2023 pm 02:18 PM

​The steps for PHP to determine the number of the foreach loop: 1. Create an array of "$fruits"; 2. Create a counter variable "$counter" with an initial value of 0; 3. Use "foreach" to loop through the array, and Increase the value of the counter variable in the loop body, and then output each element and their index; 4. Output the value of the counter variable outside the "foreach" loop to confirm which element the loop reaches.

What are the employment prospects of C#? What are the employment prospects of C#? Oct 19, 2023 am 11:02 AM

Whether you are a beginner or an experienced professional, mastering C# will pave the way for your career.

Share several .NET open source AI and LLM related project frameworks Share several .NET open source AI and LLM related project frameworks May 06, 2024 pm 04:43 PM

The development of artificial intelligence (AI) technologies is in full swing today, and they have shown great potential and influence in various fields. Today Dayao will share with you 4 .NET open source AI model LLM related project frameworks, hoping to provide you with some reference. https://github.com/YSGStudyHards/DotNetGuide/blob/main/docs/DotNet/DotNetProjectPicks.mdSemanticKernelSemanticKernel is an open source software development kit (SDK) designed to integrate large language models (LLM) such as OpenAI, Azure

PHP returns an array with key values ​​flipped PHP returns an array with key values ​​flipped Mar 21, 2024 pm 02:10 PM

This article will explain in detail how PHP returns an array after key value flipping. The editor thinks it is quite practical, so I share it with you as a reference. I hope you can gain something after reading this article. PHP Key Value Flip Array Key value flip is an operation on an array that swaps the keys and values ​​in the array to generate a new array with the original key as the value and the original value as the key. Implementation method In PHP, you can perform key-value flipping of an array through the following methods: array_flip() function: The array_flip() function is specially used for key-value flipping operations. It receives an array as argument and returns a new array with the keys and values ​​swapped. $original_array=[

PHP returns the current element in an array PHP returns the current element in an array Mar 21, 2024 pm 12:36 PM

This article will explain in detail about the current element in the array returned by PHP. The editor thinks it is very practical, so I share it with you as a reference. I hope you can gain something after reading this article. Get the current element in a PHP array PHP provides a variety of methods for accessing and manipulating arrays, including getting the current element in an array. The following introduces several commonly used techniques: 1. current() function The current() function returns the element currently pointed to by the internal pointer of the array. The pointer initially points to the first element of the array. Use the following syntax: $currentElement=current($array);2.key() function key() function returns the array internal pointer currently pointing to the element

What is the difference between foreach and for loop What is the difference between foreach and for loop Jan 05, 2023 pm 04:26 PM

Difference: 1. for loops through each data element through the index, while forEach loops through the data elements of the array through the JS underlying program; 2. for can terminate the execution of the loop through the break keyword, but forEach cannot; 3. for can control the execution of the loop by controlling the value of the loop variable, but forEach cannot; 4. for can call loop variables outside the loop, but forEach cannot call loop variables outside the loop; 5. The execution efficiency of for is higher than forEach.

.NET performance optimization technology for developers .NET performance optimization technology for developers Sep 12, 2023 am 10:43 AM

If you are a .NET developer, you must be aware of the importance of optimizing functionality and performance in delivering high-quality software. By making expert use of the provided resources and reducing website load times, you not only create a pleasant experience for your users but also reduce infrastructure costs.

See all articles