This isn't how you would iterate a dictionary. For one, it does a linear walk through its keys/values on every call to .Keys.ElementAt(i), which is really wasteful. More importantly, it's just more clunky/complicated than it needs to be.
Instead, you would use a foreach loop to get a KeyValuePairKeyValuePair<string, string> object, whose Key and Value you could then access:
foreach (var item in keyContentDictionary)
{
actionDelegatesCollection.Add((r) =>
{
r.Key = item.Key;
r.ContentBody = item.Value;
});
}
- Why do the
aKeyandaValuevariables needingneed to be re-declared in every loop iteration?
It's because your lambda is capturing the aKey and aValue variables themselves, not their value at the time of the lambda construction.
When the variables are outside the loop, then only 1 pair of variables exists in total, and each of your lambda instances captures that one pair. Each loop iteration overwrites their value, so only the last loop iterations values "stick", which are the ones you'll see when the lambda is later invoked.
This is much the same problem that C# used to have with foreach, prior to C# 5, where they made a breaking change to the language to give it the more expected behaviour. Eric Lippert's blog post does a great job of explaining that problem, which I think will help you understand your problem.
- Why is
IndexOutOfRangeExceptionbeing thrown when using a loop's iteration index to retrieve elements in theDictionaryfrom within the C# Lambda Anonymous function?
Truthfully, I don't really understand the question, but I have a vague hunch, which I'll share because you might find it useful.
I suspect you're trying to capture various index values (i) in your lambdas, and trying to use them at some later point when your lambdas are invoked. The problem is that between the time you iterated the dictionary (and say, got indices from 0 to 10), the dictionary might have shrunk (to say, only 3 elements). Those captures values between 3 and 10 will all be now out-of-bounds, at the later time when the closure is invoked and tries to use them.