score:11

Accepted answer

you're using linq. you need to perform an eager operation to make it perform the .select. tolist() is a good operator to do that. list is generic it can be assigned to ienumberable directly.

in the case where you're using linq it does lazy evaluation by default. tolist/eager operations force the select to occur. before you use one of these operators the action is not performed. it is like executing sql in ado.net kind of. if you have the statement "select * from users" that doesn't actually perform the query until you do extra stuff. the tolist makes the select execute.

score:0

actually the question is about lookup creation, which could be achieved simpler with standard linq group join:

var query = from regionid in regionids
            join location in locations
            on regionid.tolower() equals location.regionid.tolower() into g
            select new { regionid = regionid, 
                         locations = g.select(location => location.locationid) };

in this case all locations will be downloaded at once, and grouped in-memory. also this query will not be executed until you try to access results, or until you convert it to dictionary:

var locationsbyregion = query.todictionary(x => x.regionid, x => x.locations);

score:4

call tolist() or toarray() after the select(...). thus entire collection will be evaluated right there.

score:8

your closing over the variable, not the value.

make a local copy of the variable so you capture the current value from the foreach loop instead:

_locationsbyregion = new dictionary<string, ienumerable<string>>();
foreach (string regionid in regionids)
{
    var regiontoupper = regionid.toupper();
    ienumerable<string> locationids = locations
        .where(location => location.regionid.toupper() == regiontoupper)
        .select(location => location.locationid); //if i cast to an array here, it works.
    _locationsbyregion.add(regionid, locationidsids);
}

then read this:

http://msdn.microsoft.com/en-us/vcsharp/hh264182

edit - forcing a eager evaluation would also work as others have suggested, but most of the time eager evaluations end up being much slower.


Related Query

More Query from same tag