Can the debugger tell me a count/status of a foreach loop?
As a debugging one off isn't there an indexof method?
i.e.
quickwatch - someObjects.indexOf(someObject);
Added - Sorry if a bit brief.
As pointed out by Guffa this will work best if the values are unique or the default equality comparer EqualityComparer function uses a unique value (such as a custom GetHashCode/Equals overload).
public class ATest
{
public int number { get; set; }
public int boo { get; set; }
public ATest()
{
}
}
protected void Go()
{
List<ATest> list = new List<ATest>();
foreach(var i in Enumerable.Range(0,30)) {
foreach(var j in Enumerable.Range(0,100)) {
list.Add(new ATest() { number = i, boo = j });
}
}
var o =0; //only for proving concept.
foreach (ATest aTest in list)
{
DoSomthing(aTest);
//proof that this does work in this example.
o++;
System.Diagnostics.Debug.Assert(o == list.IndexOf(aTest));
}
}
This is for Visual Studio, but other IDEs should have something similar:
When you set a breakpoint you can right-click it and go to "Hit Count". You can setup some parameters there ("greater than or equal to " 0 will make it work like a regular breakpoint - so would "break always"). The interesting part is the Hit Count field (which can be reset).
This can solve the "number of iterations" part. For the total number I'm afraid you're going to have to find it yourself, assuming the collection you use has such a number readily available.
You can also set the breakpoint to fire after a very large number of hits, say a few thousands/millions (I don't know what is their limit). Then, when the "real" breakpoint fires, the one where you want to know how many times the original breakpoint was hit, you can just examine it and reset it if needed.
Is this case, if you really wanted to know what the count is, wouldn't you use a for
loop?
List<SomeObject> someObjects = ReturnListWithThousandsOfObjects();
for(int someObj= 1; someObj <= someObjects.Count; someObj++)
{
Console.WriteLine(string.Format("{0} of {1} iterations", someObj, someObjects.Count));
DoSomething.With(someObject[someObj]);
}
There will be no real difference in performance between the foreach
and the for
loops - therefore the for
loop will be a better alternative for the situation you want to achieve.