Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I am debugging my program. Can I set a start object for the foreach loop in the debug mode? For instance, I want the foreach loop to start from the 5th element of my collection.

like image 394
Gleb Avatar asked Feb 13 '23 05:02

Gleb


2 Answers

No, you cant. Foreach loop uses IEnumerable<T> where T is the type of object. So unlike for loop you cannot set initial or start index for the iteration. So you will always start from the 0th location object.

Other 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);
}
like image 148
Shaggy Avatar answered Feb 15 '23 10:02

Shaggy


Considering you are talking about debugging I'm assuming what you want to do is to break from the 5th element on etc. If this is the case then you can use a break point specifying a hit count which will break on the nth hit and so on.

See MSDN here.

like image 33
kjbartel Avatar answered Feb 15 '23 10:02

kjbartel