This is the notorious problem of “ foreach capture” and “fixed” in C # 5 (“fixed” is a strong word, as it suggests it was a “mistake”: in fact, the specification has now changed to recognize this as a common cause of confusion ) In both cases, lambda captures the variable pf , not the " pf value during this iteration", but in C # up to -5 the pf variable is technically outside the loop (therefore there is only one of them, period), where - like in C # 5 and above, the variable is limited inside the loop (so there is another variable for each goal).
In C # 4, just trick:
foreach (PresentationFile tmp in speakerAssignment.FKPresentation.PresentationFiles) { PresentationFile pf = tmp;
now pf is inside the foreach and it will work fine. Without this, there is only one pf - and since you have deferred execution to the end, the value of a single pf will be the last iteration.
An alternative solution would be: do not delay execution:
fileTypeListDict.Add(pf.ID, fileTypes.ToList());
Now it is evaluated when pf is "current", so it will have the expected results.
source share