Problem with List<IEnumerable<string>>
Hi,
Why do I get a wrong result for this simple code in LINQPad?
Output:
6
6
6
The correct output would be:
3
1
6
LINQPad v.4.42.01
.Net 4.0
Thanks,
Why do I get a wrong result for this simple code in LINQPad?
List<int> toSearch= new List<int>{100,199,95};
List<string> assets = new List<string>{"95873","95950","95935","95942","105019","95938","199999","97490","100442","100167","100167","95873"};
List<IEnumerable<string>> list = new List<IEnumerable<string>>();
foreach ( var n in toSearch)
{
IEnumerable<string> query = (from asset in assets
where asset.Contains(n.ToString())
select asset);
list.Add(query);
}
foreach (var v in list)
Console.WriteLine(v.Count());
Output:
6
6
6
The correct output would be:
3
1
6
LINQPad v.4.42.01
.Net 4.0
Thanks,
Comments
I leave it to an expert to explain
http://blogs.msdn.com/b/ericlippert/archive/2009/11/12/closing-over-the-loop-variable-considered-harmful.aspx
You can fix it by taking a copy of the variable n and using that variable in your query
foreach ( var n in toSearch) { var copyOfN = n; IEnumerable<string> query = (from asset in assets where asset.Contains(copyOfN.ToString()) select asset); list.Add(query); }