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");
forEach = function (callback) { // Do stuff... }; If you've provided one, it will loop through each item in the array, and pass in the current item in the loop, the current index, and the array itself as arguments to the callback.
The working of foreach loops is to do something for every element rather than doing something n times. There is no foreach loop in C, but both C++ and Java have support for foreach type of loop. In C++, it was introduced in C++ 11 and Java in JDK 1.5. 0 The keyword used for foreach loop is “for” in both C++ and Java.
Difference between for loop and foreach loop:for loop executes a statement or a block of statement until the given condition is false. Whereas foreach loop executes a statement or a block of statements for each element present in the array and there is no need to define the minimum or maximum limit.
Syntax. For every loop iteration, the value of the current array element is assigned to $value and the array pointer is moved by one, until it reaches the last array element.
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();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With