Before we look in detail at the services LINQ offers, there are some features that apply across all of LINQ that you should be aware of.
LINQ query syntax makes implicit use of lambdas. The
expressions that appear in
select, or most other clauses are written as
ordinary expressions, but as you’ve seen, the C# compiler turns queries
into a series of method calls, and the expressions become lambda
Most of the time, you can just write the expressions you need and they work. But you need to be wary of code that has side effects. For example, it would be a bad idea to write the sort of query shown in Example 8-8.
Example 8-8. Unhelpful side effects in a query
int x = 10000; var bigFiles = from file in GetAllFilesInDirectory(@"c:\") where new FileInfo(file).Length > x++ select file;
where clause here
increments a variable declared outside the scope of the query.
This is allowed (although it’s a bad idea) in LINQ to Objects. Some LINQ providers, such as the ones you would use with databases, will reject such a query at runtime.
This will have the potentially surprising result that the query
could return different files every time it runs, even if the underlying
data has not changed. Remember, the expression in the
where clause gets converted into an anonymous
method, which will be invoked once for every item in the query’s source.
The first time this runs, the local
x variable will be incremented once for every file ...