Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can the debugger tell me a count/status of a foreach loop?

Suppose I have the following code:

List<SomeObject> someObjects = ReturnListWithThousandsOfObjects();

foreach(SomeObject someobject in someObjects)
{
   DoSomething.With(someObject);
}

And also suppose that after a minute of running I put a breakpoint on DoSomething.With(someObject);.

The debugger breaks for me just fine. But now I want to know what point am I at in my iteration of the list (assume the list is unordered/has no key).

Is there a way for the debugger to say "the foreach has run 532 of 2321 iterations"?

like image 318
Vaccano Avatar asked Jun 09 '11 21:06

Vaccano


1 Answers

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

    }
like image 125
Mike Miller Avatar answered Sep 24 '22 15:09

Mike Miller