SoFunction
Updated on 2025-04-13

C# programming: Comparative analysis with foreach loop

C# programming: Comparative analysis with foreach loop

Updated: March 26, 2025 09:18:25 Author: AitTech
This article mainly introduces C# programming: a comparison and analysis with foreach loops, which has good reference value. I hope it will be helpful to everyone. If there are any errors or no complete considerations, I hope you will be very encouraged.

Comparison of C# and foreach loops

In C#,List<T>.ForEachMethods and traditionalforeachLoops 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 signaturepublic void ForEach(Action<T> action)
  • typeForEachyesList<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 oneAction<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 callForEachand the traversal stops.

Traditional foreach loop

  • grammarforeach (var item in collection)
  • typeforeachIt is a keyword in C# language, used to traverse itIEnumerable<T>orIEnumerableCollection 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 bodybreakcontinueandreturnStatements 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&lt;int&gt; numbers = new List&lt;int&gt; { 1, 2, 3, 4, 5 };

        // Use Method        (number =&gt;
        {
            (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 =&gt;
            {
                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 usingbreakcontinueorreturn). TraditionalforeachLoops 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.

  • C#
  • foreach
  • cycle

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-05
  • C# 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-01
  • C# 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-12
  • A 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 operations
    2016-01-01
  • ajaxFileUpload 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 it
    2017-12-12
  • Steps 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-01
  • How 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-07
  • Use 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-08
  • Note 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-04
  • Unity 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

Latest Comments