So I’m trying to understand IQueryable<T>. A tutorial I’m reading suggests using it but not really sure why. The code simply returns some values using LINQ to SQL. I’ve done this plenty of times in the past, but not using IQueryable<T>
Why use it with my functions that return more than 1 value?
Here’s my code:
public IQueryable<Items> GetItems()
{
return from item in db.Items
where item.IsActive == true
orderby item.ItemNumber
select item;
}
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:
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 anIEnumerable<T>, and its provider computes the final SQL when you try to invoke theGetEnumerator()method on it. You can either do this explicitly by calling it, or implicitly by using it in aforeachstatement. Also, extension methods likeToArray()will do one of these internally, thus producing the same effect.