Yes, the first version is much slower. In the end, I assume that you are dealing with these types:
public class SlowCountProvider { public int Count { get { Thread.Sleep(1000); return 10; } } } public class KeyValuesWithSlowCountProvider { public SlowCountProvider KeyValues { get { return new SlowCountProvider(); } } }
Here, your first cycle will take ~ 10 seconds, while your second cycle will take ~ 1 second.
Of course, you can argue that the assumption that you are using this code is unjustified, but I believe that the correct answer will depend on the respective types, and the question does not indicate what these types are.
Now, if you are really dealing with a type where access to KeyValues and Count cheap (which is likely), I would not expect that there would be a big difference. Keep in mind, I almost always prefer to use foreach , where possible:
foreach (var pair in dwhSessionDto.KeyValues) {
This way you will never need an account. But then you did not say what you are trying to do inside the loop. (Hint: for more helpful answers, provide more information .)
Jon skeet
source share