Introduction
When working with LINQ in C#, developers often see two important interfaces:
IEnumerable
IQueryable
Both are used to query data collections, but they work differently, especially when working with databases.
Understanding the difference helps developers write faster and more efficient applications.
In this article, we will understand the difference between IEnumerable and IQueryable with simple examples.
What is IEnumerable?
IEnumerable is an interface used for iterating over in-memory collections such as:
Lists
Arrays
Collections
It executes the query after retrieving data from the database.
Simple Example
using System;
using System.Collections.Generic;
using System.Linq;
class Program
{
static void Main()
{
List<int> numbers = new List<int> { 1,2,3,4,5,6,7,8 };
IEnumerable<int> result = numbers.Where(n => n > 4);
foreach (var item in result)
{
Console.WriteLine(item);
}
}
}
Output
5
6
7
8
Important Point
Here the data is already loaded into memory, and then LINQ filters it.
So the filtering happens in the application memory.
What is IQueryable?
IQueryable is used to query data from external data sources, such as databases.
Instead of loading all data first, it builds a query and sends it to the database server.
The database performs the filtering.
Example with Database Concept
using System;
using System.Linq;
class Program
{
static void Main()
{
IQueryable<int> data = new List<int> {1,2,3,4,5,6}.AsQueryable();
var result = data.Where(x => x > 3);
foreach (var item in result)
{
Console.WriteLine(item);
}
}
}
In real projects, IQueryable is commonly used with Entity Framework.
Example
var students = db.Students.Where(s => s.Age > 18);
Here the query is converted into SQL like:
SELECT * FROM Students WHERE Age > 18
The filtering happens inside the database, not in memory.
Join the conversation! Your thoughts help the community grow.