While debugging, how can I start a foreach loop at an arbitrary position in the enum?

I am debugging my program. Can I set the starting object for a loop foreach

in debug mode? For example, I want the loop to foreach

start at the 5th item in my collection.

+3


source to share


5 answers


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

      

+5


source


Considering you are talking about debugging, I assume you want to do this to get out of the 5th item, etc. If so, then you can use a breakpoint that determines the number of hits that will break on the nth press, etc.



See MSDN here .

+1


source


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 statement numbers

    .
  • 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.

+1


source


@ 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]
}

      

0


source


foreach

does not necessarily work with a collection that even has a specific order. consider a Dictionary<T>

or ConcurrentBag<T>

. so no, this is not possible in general, especially without code changes (which might change the problem you are trying to debug).

0


source







All Articles