search
HomeBackend DevelopmentC#.Net TutorialIn-depth understanding of the use of foreach traversal in C#

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

}

List:


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

public List<T>.Enumerator GetEnumerator()

{

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

}

Dictionary


// 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
C# .NET in the Modern World: Applications and IndustriesC# .NET in the Modern World: Applications and IndustriesMay 08, 2025 am 12:08 AM

C#.NET is widely used in the modern world in the fields of game development, financial services, the Internet of Things and cloud computing. 1) In game development, use C# to program through the Unity engine. 2) In the field of financial services, C#.NET is used to develop high-performance trading systems and data analysis tools. 3) In terms of IoT and cloud computing, C#.NET provides support through Azure services to develop device control logic and data processing.

C# .NET Framework vs. .NET Core/5/6: What's the Difference?C# .NET Framework vs. .NET Core/5/6: What's the Difference?May 07, 2025 am 12:06 AM

.NETFrameworkisWindows-centric,while.NETCore/5/6supportscross-platformdevelopment.1).NETFramework,since2002,isidealforWindowsapplicationsbutlimitedincross-platformcapabilities.2).NETCore,from2016,anditsevolutions(.NET5/6)offerbetterperformance,cross-

The Community of C# .NET Developers: Resources and SupportThe Community of C# .NET Developers: Resources and SupportMay 06, 2025 am 12:11 AM

The C#.NET developer community provides rich resources and support, including: 1. Microsoft's official documents, 2. Community forums such as StackOverflow and Reddit, and 3. Open source projects on GitHub. These resources help developers improve their programming skills from basic learning to advanced applications.

The C# .NET Advantage: Features, Benefits, and Use CasesThe C# .NET Advantage: Features, Benefits, and Use CasesMay 05, 2025 am 12:01 AM

The advantages of C#.NET include: 1) Language features, such as asynchronous programming simplifies development; 2) Performance and reliability, improving efficiency through JIT compilation and garbage collection mechanisms; 3) Cross-platform support, .NETCore expands application scenarios; 4) A wide range of practical applications, with outstanding performance from the Web to desktop and game development.

Is C# Always Associated with .NET? Exploring AlternativesIs C# Always Associated with .NET? Exploring AlternativesMay 04, 2025 am 12:06 AM

C# is not always tied to .NET. 1) C# can run in the Mono runtime environment and is suitable for Linux and macOS. 2) In the Unity game engine, C# is used for scripting and does not rely on the .NET framework. 3) C# can also be used for embedded system development, such as .NETMicroFramework.

The .NET Ecosystem: C#'s Role and BeyondThe .NET Ecosystem: C#'s Role and BeyondMay 03, 2025 am 12:04 AM

C# plays a core role in the .NET ecosystem and is the preferred language for developers. 1) C# provides efficient and easy-to-use programming methods, combining the advantages of C, C and Java. 2) Execute through .NET runtime (CLR) to ensure efficient cross-platform operation. 3) C# supports basic to advanced usage, such as LINQ and asynchronous programming. 4) Optimization and best practices include using StringBuilder and asynchronous programming to improve performance and maintainability.

C# as a .NET Language: The Foundation of the EcosystemC# as a .NET Language: The Foundation of the EcosystemMay 02, 2025 am 12:01 AM

C# is a programming language released by Microsoft in 2000, aiming to combine the power of C and the simplicity of Java. 1.C# is a type-safe, object-oriented programming language that supports encapsulation, inheritance and polymorphism. 2. The compilation process of C# converts the code into an intermediate language (IL), and then compiles it into machine code execution in the .NET runtime environment (CLR). 3. The basic usage of C# includes variable declarations, control flows and function definitions, while advanced usages cover asynchronous programming, LINQ and delegates, etc. 4. Common errors include type mismatch and null reference exceptions, which can be debugged through debugger, exception handling and logging. 5. Performance optimization suggestions include the use of LINQ, asynchronous programming, and improving code readability.

C# vs. .NET: Clarifying the Key Differences and SimilaritiesC# vs. .NET: Clarifying the Key Differences and SimilaritiesMay 01, 2025 am 12:12 AM

C# is a programming language, while .NET is a software framework. 1.C# is developed by Microsoft and is suitable for multi-platform development. 2..NET provides class libraries and runtime environments, and supports multilingual. The two work together to build modern applications.

See all articles

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

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.