While debugging, how can I start a foreach loop at an arbitrary position in the enum?
No, you cannot. In the Foreach loop IEnumerable<T>
, where T is the type of the object. Therefore, unlike for a loop, you cannot set a start or start index for an iteration. This way you will always start at the 0th location object.
Another option is to use linq as shown below.
//Add using System.Linq statement at top.
int[] numbers = new int[] { 1,2,3,4,5,6,7,8};
foreach(var num in numbers.Skip(5))
{
Console.WriteLine(num);
}
source to share
An easy way to set the initial object is to overwrite the variable you are listing in the loop.
To illustrate, consider the following cycle foreach
.
IEnumerable<int> numbers = Enumerable.Range(1, 100);
foreach (int n in numbers)
{
Console.WriteLine(n);
}
- Set a breakpoint in a statement
numbers
in a loop initializer, or go to a loop, but don't run the statementnumbers
. -
Use an immediate window to override the value
numbers
:numbers = numbers.Skip(5); // or Enumerable.Skip(numbers, 5)
-
Continue debugging; the loop is executed from the sixth element.
If your loop uses inline computation like this, you're out of luck. Use hit-count breakpoint instead .
foreach (int n in Enumerable.Range(1, 100)) // no way to change enumeration.
{
Console.WriteLine(n);
}
Note: After executing the statement, the numbers
debugger will cache your enum so that it can no longer be modified and affect the loop. You can observe this by executing the loop construct.
source to share
@ Shaggy's answer is probably the simplest, but it's good to know that the old fashioned loop is the fastest and lets you skip index 0.
for(int x = 4; x < numbers.Length; x++)
{
// Do anything with numbers[x]
}
While I wouldn't recommend it (it's really bad code), you could make this loop behave differently when debugging as you asked:
#if DEBUG
for(int x = 4; x < numbers.Length; x++)
#else
for(int x = 0; x < numbers.Length; x++)
#endif
{
// Do anything with numbers[x]
}
source to share