23.4. Debugging and Execution

One of the things you should be aware of with LINQ is that the queries are not executed until they are used. In fact, each time you use a LINQ query you will find that the query is re-executed. This can potentially lead to some issues in debugging and some unexpected performance issues if you are executing the query multiple times. In the code you have seen so far, we have declared the LINQ statement and then passed the results object to the ObjectDumper, which in turn iterates through the query results. If we were to repeat this call to the ObjectDumper, it would again iterate through the results.

Unfortunately, this delayed execution can mean that LINQ statements are hard to debug. If you select the statement and insert a breakpoint, all that will happen is that the application will stop where you have declared the LINQ statement. If you step to the next line, the results object will simply state that it is an "In-Memory Query." In C# the debugging story is slightly better because you can actually set breakpoints within the LINQ statement. As you can see from Figure 23-10, the breakpoint on the conditional statement has been hit. From the call stack you can see that the current execution point is no longer actually in the FinalQuery method; it is in fact within the ObjectDumper.Write method.

Figure 23.10. Figure 23-10

If you need to force the execution of a LINQ query, you can call ToArray or ToList on the results object. This will force the query to execute, returning an Array or List of the appropriate type. You can then use this array in other queries, reducing the need for the LINQ query to be executed multiple times.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.118.24.30