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!

C# and .NET adapt to the needs of emerging technologies through continuous updates and optimizations. 1) C# 9.0 and .NET5 introduce record type and performance optimization. 2) .NETCore enhances cloud native and containerized support. 3) ASP.NETCore integrates with modern web technologies. 4) ML.NET supports machine learning and artificial intelligence. 5) Asynchronous programming and best practices improve performance.

C#.NETissuitableforenterprise-levelapplicationswithintheMicrosoftecosystemduetoitsstrongtyping,richlibraries,androbustperformance.However,itmaynotbeidealforcross-platformdevelopmentorwhenrawspeediscritical,wherelanguageslikeRustorGomightbepreferable.

The programming process of C# in .NET includes the following steps: 1) writing C# code, 2) compiling into an intermediate language (IL), and 3) executing by the .NET runtime (CLR). The advantages of C# in .NET are its modern syntax, powerful type system and tight integration with the .NET framework, suitable for various development scenarios from desktop applications to web services.

C# is a modern, object-oriented programming language developed by Microsoft and as part of the .NET framework. 1.C# supports object-oriented programming (OOP), including encapsulation, inheritance and polymorphism. 2. Asynchronous programming in C# is implemented through async and await keywords to improve application responsiveness. 3. Use LINQ to process data collections concisely. 4. Common errors include null reference exceptions and index out-of-range exceptions. Debugging skills include using a debugger and exception handling. 5. Performance optimization includes using StringBuilder and avoiding unnecessary packing and unboxing.

Testing strategies for C#.NET applications include unit testing, integration testing, and end-to-end testing. 1. Unit testing ensures that the minimum unit of the code works independently, using the MSTest, NUnit or xUnit framework. 2. Integrated tests verify the functions of multiple units combined, commonly used simulated data and external services. 3. End-to-end testing simulates the user's complete operation process, and Selenium is usually used for automated testing.

Interview with C# senior developer requires mastering core knowledge such as asynchronous programming, LINQ, and internal working principles of .NET frameworks. 1. Asynchronous programming simplifies operations through async and await to improve application responsiveness. 2.LINQ operates data in SQL style and pay attention to performance. 3. The CLR of the NET framework manages memory, and garbage collection needs to be used with caution.

C#.NET interview questions and answers include basic knowledge, core concepts, and advanced usage. 1) Basic knowledge: C# is an object-oriented language developed by Microsoft and is mainly used in the .NET framework. 2) Core concepts: Delegation and events allow dynamic binding methods, and LINQ provides powerful query functions. 3) Advanced usage: Asynchronous programming improves responsiveness, and expression trees are used for dynamic code construction.

C#.NET is a popular choice for building microservices because of its strong ecosystem and rich support. 1) Create RESTfulAPI using ASP.NETCore to process order creation and query. 2) Use gRPC to achieve efficient communication between microservices, define and implement order services. 3) Simplify deployment and management through Docker containerized microservices.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

Zend Studio 13.0.1
Powerful PHP integrated development environment

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

SublimeText3 Mac version
God-level code editing software (SublimeText3)

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft