Does LINQ cache computed values?

.net, c#, clr4.0, linq

Solution

It has been a while since I dug through this code but, IIRC, the way `Select` works is to simply cache the `Func` you supply it and run it on the source collection one at a time. So, for each element in the outer range, it will run the inner `Select/Aggregate` sequence as if it were the first time. There isn't any built-in caching going on -- you would have to implement that yourself in the expressions.

If you wanted to figure this out yourself, you've got three basic options:

- Compile the code and use `ildasm` to view the IL; it's the most accurate but, especially with lambdas and closures, what you get from IL may look nothing like what you put into the C# compiler.

- Use something like dotPeek to decompile System.Linq.dll into C#; again, what you get out of these kinds of tools may only approximately resemble the original source code, but at least it will be C# (and dotPeek in particular does a pretty good job, and is free.)

- My personal preference - download the .NET 4.0 Reference Source and look for yourself; this is what it's for :) You have to just trust MS that the reference source matches the actual source used to produce the binaries, but I don't see any good reason to doubt them.

- As pointed out by @AllonGuralnek you can set breakpoints on specific lambda expressions within a single line; put your cursor somewhere inside the body of the lambda and press F9 and it will breakpoint just the lambda. (If you do it wrong, it will highlight the entire line in the breakpoint color; if you do it right, it will just highlight the lambda.)

Problem

Suppose I have the following code: ``` var X = XElement.Parse (@" <ROOT> <MUL v='2' /> <MUL v='3' /> </ROOT> "); Enumerable.Range (1, 100) .Select (s => X.Elements () .Select (t => Int32.Parse (t.Attribute ("v").Value)) .Aggregate (s, (t, u) => t * u) ) .ToList () .ForEach (s => Console.WriteLine (s)); ``` What is the .NET runtime actually doing here? Is it parsing and converting the attributes to integers each of the 100 times, or is it smart enough to figure out that it should cache the parsed values and not repeat the computation for each element in the range? Moreover, how would I go about figuring out something like this myself? Thanks in advance for your help.

Original source