I have a space question about Linq expressions that are defined in a loop. The following LinqPad C # program demonstrates behavior:
void Main() { string[] data=new string[] {"A1", "B1", "A2", "B2" }; string[] keys=new string[] {"A", "B" }; List<Result> results=new List<Result>(); foreach (string key in keys) { IEnumerable<string> myData=data.Where (x => x.StartsWith(key)); results.Add(new Result() { Key=key, Data=myData}); } results.Dump(); }
In principle, โAโ should have data [A1, A2] and โBโ should have data [B1, B2].
However, when starting, โAโ gets the data [B1, B2], just like BIe, the last expression is evaluated for all instances of the result.
Given that I declared "myData" in the loop, why does it behave as if I declared it outside the loop? EG works as I would expect if I did this:
void Main() { string[] data=new string[] {"A1", "B1", "A2", "B2" }; string[] keys=new string[] {"A", "B" }; List<Result> results=new List<Result>(); IEnumerable<string> myData; foreach (string key in keys) { myData=data.Where (x => x.StartsWith(key)); results.Add(new Result() { Key=key, Data=myData}); } results.Dump(); }
I get the desired result, if I force the evaluation inside the iteration, this is not my question.
I ask why "myData" seems to be split between iterations, given that I declared it as part of a single iteration?
Someone is calling Jon Skeet ...; ^)