How can I use 'continue' and `break` in the extension method?

I have defined the following extension method:

public static void ForEach<T>(this IEnumerable<T> sequence, Action<T> action)
{
   foreach (T obj in sequence)
   { 
      action(obj); 
   } 
}

Then I can use it like:

new [] {1, 2, 3} // an IEnumerable<T>
.ForEach(n => 
{
  // do something 
});

I want to be able to use continue, and breakthe inside of my extension method so that I can:

new [] {1, 2, 3}
.ForEach(n => 
{
    // this is an overly simplified example
    // the n==1 can be any conditional statement
    // I know in this case I could have just used .Where
    if(n == 1) { continue; }
    if(n == -1) { break; }      
    // do something 
});

Are these keywords are used only in cycles for, foreach, whileor do-while?

+4
source share
3 answers

Can these keywords be used only in for, foreach, while loops?

Yes. These statements are limited to loop types. As the docs say :

continue while, do, for foreach, .

:

break , . , , .

foreach, , . , foreach , .

, ?:

var arr = new [] {1, 2, 3}
foreach (int number in arr)
{
    if(n == 1) { continue; }      
    if(n == -1) { break; }      
}
+7

Yuval , - :

Action<T> Func<T, bool>, T bool.

"" , , .

"break" , bool , , :

public static void ForEach<T>(this IEnumerable<T> sequence, Func<T, bool> action)
{
  foreach (T obj in sequence)
  { 
    if (!action(obj)) 
      break;
  }
}

new [] {1, 2, 3}.ForEach(n => 
{
    if(n == 1) { return true;}      
    if(n == -1) { return false; }  

    // do something 
    ...
    return true;
});
+3

Yes, these keywords are limited while, do, forand foreach(as Yuval indicated).

This code will be about the same as you ask:

bool shouldBreak = false;

new [] {1, 2, 3}
.ForEach(n => 
{
    if (!shouldBreak)
    {
        if(n == 1) { /* no action */ }      
        else if(n == -1) { shouldBreak = true; }
        else
        {
            // do something 
        }
    }
});
+1
source

Source: https://habr.com/ru/post/1598224/


All Articles