开发者

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

Python's for and while l开发者_StackOverflow社区oops 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");


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


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.


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();
}


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();
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜