C# programming: Comparative analysis with foreach loop
Comparison of C# and foreach loops
In C#,List<T>.ForEach
Methods and traditionalforeach
Loops are all used to iterate over elements in a list and perform operations on each element, but there are some key differences between them.
List<T>.ForEach method
-
Method signature:
public void ForEach(Action<T> action)
-
type:
ForEach
yesList<T>
An instance method of the class. - Thread safety: Not thread-safe. If the list is modified during the traversal (such as adding or removing elements), an exception may be caused.
-
Entrustment: It accepts one
Action<T>
Delegate, which defines the action to be performed on each element in the list. -
Exception handling: If the delegate throws an exception during execution, it will propagate to the call
ForEach
and the traversal stops.
Traditional foreach loop
-
grammar:
foreach (var item in collection)
-
type:
foreach
It is a keyword in C# language, used to traverse itIEnumerable<T>
orIEnumerable
Collection of interfaces. - Thread safety: Also not thread-safe, but provides more flexibility to handle exceptions and modify collections within the loop body (although this is usually not recommended as it can lead to undefined behavior).
-
flexibility: Can be used in the circulation body
break
、continue
andreturn
Statements to control the flow of the loop. - Exception handling: Exceptions can be caught and processed in the loop body without stopping the entire traversal immediately.
Give an example
using System; using ; class Program { static void Main() { List<int> numbers = new List<int> { 1, 2, 3, 4, 5 }; // Use Method (number => { (number); // Note: break, continue or return cannot be used here to control the loop }); // Use traditional foreach loops foreach (var number in numbers) { (number); // You can use break, continue or return // if (number == 3) break; // This will jump out of the loop // if (number == 3) continue; // This will skip the current iteration and continue to the next time // if (number == 3) return; // This will exit the entire method (if this is inside the method) } // Another example: exception handling try { (number => { if (number == 3) throw new InvalidOperationException("Number 3 is not allowed."); (number); }); } catch (Exception ex) { ("Exception caught in ForEach: " + ); } try { foreach (var number in numbers) { if (number == 3) { // Exceptions can be caught here, or the exception can be propagated // throw new InvalidOperationException("Number 3 is not allowed."); ("Skipping number 3 due to potential issue."); continue; // Choose to skip the number 3 instead of throwing an exception } (number); } } catch (Exception ex) { ("Exception caught in foreach: " + ); } } }
In this example,The method concisely traverses the list and performs operations on each element, but it does not allow control of the flow of the loop (such as using
break
、continue
orreturn
). Traditionalforeach
Loops provide more flexibility, including exception handling and loop control.
Summarize
The above is personal experience. I hope you can give you a reference and I hope you can support me more.
Related Articles
Detailed explanation of C# implementation of the application of multiple font formats in Excel cells
In Excel, you can set various different styles to strings in cells. This article will take C# and code as an example to introduce how to apply multiple font styles in the same cell of Excel. Those who are interested can learn about it.2022-05-05C# serial debugging tool
This article introduces the method of implementing serial debugging tools in C#, and the article introduces it in detail through sample code. It has certain reference value for everyone's study or work. Friends who need it can refer to it.2022-01-01C# implements RMB capital conversion example code
This article mainly introduces C# to realize capital conversion of RMB. Friends who need it can refer to it.2013-12-12A brief discussion on the issue of C# pointer
In C#, sometimes it is hoped to operate memory through pointers, which can improve efficiency. We can use the unsafe keyword to modify program segments containing pointer operations2016-01-01ajaxFileUpload plugin, C# returns the solution to Json data error problem
This article mainly introduces the ajaxFileUpload plug-in, C# returns the solution to Json data error. Friends who need it can refer to it2017-12-12Steps for C# to operate XML files
In this article, the editor has shared with you the teaching content about the steps of C# operation XML files. Interested friends can learn it.2019-01-01How to write C# port scanner
This article mainly introduces the writing method of C# port scanner in detail. The sample code in the article is introduced in detail and has certain reference value. Interested friends can refer to it.2022-07-07Use of C# concurrent combat records
This article mainly introduces relevant information about the use of C# concurrent combat records. The article introduces the example code in detail, which has certain reference learning value for everyone to learn or use C#. If you need it, let’s learn together.2019-08-08Note records for the use of nullable reference types in C# 8.0
This article mainly introduces you to the relevant information about the use of nullable reference types in C# 8.0. The article introduces the sample code in detail, which has a certain reference learning value for everyone to learn or use C#. If you need it, let’s learn together.2019-04-04Unity Shader achieves 3D page turn effect
This article mainly introduces the 3D page turn effect of Unity Shader and Plane to achieve page turn effect. The sample code in the article is introduced in detail and has certain reference value. Interested friends can refer to it.2021-07-07