IQueryable
Learn expression-based queries with IQueryable.
What is IQueryable?
IQueryable<T> extends IEnumerable<T> and carries an expression tree and a provider. LINQ providers (e.g. EF Core) translate this expression tree to SQL.
Because of this, calls like Where and Select on IQueryable do not execute in memory — they add to the expression tree. The query runs when you iterate with foreach or call ToList; this is called deferred execution.
IQueryable vs IEnumerable
IEnumerable<T> executes in memory: LINQ methods run directly on the collection. IQueryable<T> translates the expression tree into a remote query; for example, filtering happens in the SQL database.
The same Where call means different things on the two interfaces. On an in-memory list, LINQ-to-Objects runs; on a database, LINQ-to-Entities runs. That is why IQueryable is preferred for large data.
Exercise Build an IQueryable and get Count
Convert the array int[] numbers = { 1, 2, 3, 4, 5 }; to IQueryable<int> with .AsQueryable() and assign it to query. Filter with var filtered = query.Where(n => n > 2);. Print filtered.Count() with Console.WriteLine.
Show example solution
Build the query with IQueryable<int> query = numbers.AsQueryable();. Filter with var filtered = query.Where(n => n > 2);. Print with Console.WriteLine(filtered.Count());.
Example solution:
using System;
using System.Linq;
class Program
{
static void Main()
{
int[] numbers = { 1, 2, 3, 4, 5 };
IQueryable<int> query = numbers.AsQueryable();
var filtered = query.Where(n => n > 2);
Console.WriteLine(filtered.Count());
}
}
Test yourself
-
What does IQueryable hold?
- Only the data
- A delegate
- An expression tree and a provider
- A Type object
Show answer
An expression tree and a provider — Correct. IQueryable holds an expression tree and a provider.
-
Complete the IQueryable type
IQueryable<____> query = new int[] { 1, 2, 3 }.AsQueryable();Show answer
IQueryable<int> query = new int[] { 1, 2, 3 }.AsQueryable(); -
Match the interface to its behavior
- IEnumerable<T>
- Executes in memory
- IQueryable<T>
- Holds an expression tree
- Expression
- Query data
- Provider
- Translates