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 canreturn
to avoid executing code below the loopUse a boolean variable you can set before you
break
, and test that after the loopUse
goto
instead ofbreak
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();
}
精彩评论