How to implement for-else and foreach-else in C# similar to Python's for-else and while-else?

18,184

Solution 1

The Python Construct for foreach-else is like this:

foreach( elem in collection )
{
    if( condition(elem) )
        break;
}
else
{
    doSomething();
} 

The else only executes if break is not called during the foreach loop

A C# equivalent might be:

bool found = false;
foreach( elem in collection )
{
    if( condition(elem) )
    {
        found = true;
        break;
    }
}
if( !found )
{
    doSomething();
}

Source: The Visual C# Developer Center

Solution 2

Sure:

  • Use one of the fancy suggestions by the other posters

  • Use a method that performs the loop, instead of break, you can return to avoid executing code below the loop

  • Use a boolean variable you can set before you break, and test that after the loop

  • Use goto instead of break

It's a weird pattern though if you ask me. "Foreach" is always started so the word "else" does not make sense there.

Solution 3

Googling it gave me that : http://www-jo.se/f.pfleger/.net-for-else

public static void ForEachElse<TSource>(
this IEnumerable<TSource> source,
Func<TSource>,
bool action,
Action @else
)  // end of parameters
{
foreach (var i in source)
  {
    if (!action(i))
      {
        return;
      }
  }
   @else();
}

Solution 4

If you're referring to the for-else and while-else constructs in Python, there is a basic IEnumerable<T> extension method that simulates a foreach-else described in this article, with the following implementation:

public static void ForEachElse<TSource>(
    this IEnumerable<TSource> source,
    Func<TSource, bool> action, Action @else)
{
    foreach (var i in source)
    {
        if (!action(i))
        {
            return;
        }
    }
    @else();
}
Share:
18,184
LEMUEL  ADANE
Author by

LEMUEL ADANE

I am a Filipino.

Updated on July 27, 2022

Comments

  • LEMUEL  ADANE
    LEMUEL ADANE almost 2 years

    Python's for and while loops include an optional else clause which execute if the loop exits normally (i.e. without a break statement). For example, in Python you could code:

    for x in range(3):
        print(x)
    else
        print("The loop exited normally")
    

    And the output will be:

    0
    1
    2
    The loop exited normally
    

    How would you accomplish something similar in C# in order to code something like the following:

    for (int i = 0; i < 3; i++)
    {
        Console.WriteLine(x);                  
    }
    else
        Console.WriteLine("The loop exited normally");
    
    • leppie
      leppie almost 13 years
      Unless you actually give full definitions of what these magical constructs do, the question aint real.
    • BoltClock
      BoltClock almost 13 years
      Sounds suspiciously Pythonic...
    • Peter
      Peter almost 13 years
      Give us the scenario you want to use these constructions, I bet you can always put a if - else around your for or foreach loop.
    • BoltClock
      BoltClock almost 13 years
      I doubt pseudo-code was what leppie had in mind about "full definitions"...
  • Jon Egerton
    Jon Egerton almost 13 years
    Aaargh - Goto. Really? <shivers/>
  • Adrian Ratnapala
    Adrian Ratnapala almost 10 years
    @JonEgerton, while I wouldn't quite use a goto here, I wouldn't condemn it either. The python for-else construct is just a special case goto. If you roll-your own goto, then you still have the same control of flow and have therefore not spagetified your code. Touble is, that you might accidentally spagetify it in some later change.
  • ArtOfWarfare
    ArtOfWarfare about 7 years
    I almost like the suggestion of goto, except it allows other code to enter it.