views:

91

answers:

3

I thought I'd seen somewhere a while back an example of where clause which called a function that gave a bool result ,and I can't find it again so I'll outline my problem.

I have a collection

Dictionary< string, KeyValuePair < int, int >>  

in which I want to have a query for the string key. On the surface that is simple but unfortunately the string (over which I have no control) is an encoded co-ordinate of a grid cell.

The query is to retrieve entries (as the type of Dictionary) which fall into a certain part of the grid. Placing a function call cells.Where(c => isWithinArea(c.Key, area)) compiles but does not work. The function never gets called.

I would welcome any suggestions to make this work with a minimum of fuss.

+11  A: 

The most likely reasons the function is never called would be if the sequence you're "where-ing" has no elements, or you are never invoking the enumerator at all. LINQ is lazy-evaluated, which means none of the expressions you've provided are actually invoked until you start to foreach or ToList().

Rex M
I'm guessing it's the latter. Good catch.
Steven Sudit
Yeah, I bet the latter is exactly the issue here. +1
Pandincus
A: 
cells.Keys.Where(key => isWithinArea(key, area))
David B
A: 

Thanks for your replies. Yes I did forget the ToList(), silly me. You'd think I know that by now. Then I do a ToDictionary() to the result to conveert it back to a dictionary of the same format so I can access items directly by the key. I'm still trying to make it work in a single line.

BigOldSofty
@BigOldSofty feel free to click the large "check" next to the answer which solves your problem.
Rex M