Hi Steve,
(Still in .Net 2.0, so I can't try it yet).
Are you saying that if you did
Dim myList As New List(Of Integer)
'<Snip> Init myList with 1,2,3,4,5,6,7,8,9
Dim myEvenList = (From i In myList Where i / 2 = i \ 2).ToList
then did
'<Snip> Add to myList 10,11,12,13,14
then displayed the contents of myEvenList, you would get
2,4,6,8,10,12,14?
I guess that's okay, but the code doesn't read that way to me. What you
describe sounds more like a filter on a dataview. What if you wanted just
the even numbers there were in there to start with, but not the ones added
later?
Yes and no. In the example I listed, I called the .ToList method of
myEvenList which in turn caused the query to immediately execute and store
its results (as at that time) into that List<T> variable. Had I not called
that method, then the behaviour you described (output includes 10, 12, 14)
would occur. As you correctly point out, it is actually a filter but that
isn't necessarily un-intuitive. If you think of it as just a SQL query (but
one that executes on an in-memory variable like an array) then the results
of a SQL query are always dependent on what data is in the source table at
the time of execution.
It's actually very useful in the sense that you can have an IEnumerable
variable which in this case always returns the even numbers from myList no
matter how many times you modify the content of myList. Alternatively you
can just call .ToList (or .ToArray, or .ToDictionary) and take a snapshot
right then and there (essentially by running the query and copying the
results into the appropriate generic variable).
There are many parts of Linq that aren't all that intuitive or necessarily
readable until you know exactly what the syntax is (Lambda expressions
anyone?) and at first glance it looks like ass-backward SQL code, but the
power of it is immense and I'm only scratching the surface with what I'm
using it for. I'm a lot more excited about what I can use Linq for than I
am over the WPF/WCF/WF/WWF/WWE/Smackdown technologies that MS are ramming
down everyone's throats at the moment, and have found it to be one of the
most useful additions to the language. Things like anonymous types and type
inference were also added to support Linq in the first place, and they too
are very welcome side effects.
-Alex