IQueryable represents the query as an expression tree without evaluating it on the server. This lets you specify further processing before actually generating SQL.
In the above case, this means that you can do stuff with the result of calling GetItems(), and have the original query and the extra stuff sent as a single query:
var recentItems = from item in GetItems()
where item.Timestamp > somedate
select item;
foreach (var item in recentItems)
{
// Do something with an active recent item.
}
Nothing is sent to the server until we try to consume the result in the foreach loop. At that point, the LINQ-to-SQL provider assesses the entire expression, including the bits generated inside GetItems()
and the bits specified after, and emits a single SQL statement that selects all items that are both active and recent.
To clarify a technicality, the IQueryable<T>
is an IEnumerable<T>
, and its provider computes the final SQL when you try to invoke the GetEnumerator()
method on it. You can either do this explicitly by calling it, or implicitly by using it in a foreach
statement. Also, extension methods like ToArray()
will do one of these internally, thus producing the same effect.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…