Linq Part 3 – Query Format

This entry is part of a series, Linq»

It is very easy when you are familiar with SQL to constrain yourself to treating Linq queries in a similar fashion and not take advantage of some of the new features that Linq allows. Of course, Linq does impose its own constraints, as does each Linq provider, so it isn’t always easier.

It is definitely worth getting your head around the fact that in Linq, you can query a query.  With some providers, this might mean that you are querying the results of a query, but with others, it can mean that you are simply building another query, which will only actually be executed when you try to retrieve the results.

For example,

Dim q = From p in DataContext.People Where p.Surname=”Smith”

q = From p in q Where p.FirstName=”John”

In Linq to SQL, this is perfectly efficient as it will only run SELECT * FROM Person WHERE Surname=’Smith’ AND FirstName=’John’ or something similar.

Equally, you can also combine multiple queries into a single statement, such as…

Dim q = From p in DataContext.People Select p.ID, p.Surname Order By p.Surname Select ID

…and of course you don’t need to worry about the order of the statements – notice a Select can come after an Order By!  The thing to remember is that each Select/Group effectively creates a different context (as in a variable context), so you have different variables available at each point in the query.

No related posts.

Tags: , , , ,

Leave a Reply