The difference between IEnumerable and IQueryable is one of the most important interview questions in C# and Entity Framework Core.
🔹 Main Difference
| Feature | IEnumerable | IQueryable |
|---|---|---|
| Namespace | System.Collections | System.Linq |
| Execution | In-memory | Database / remote |
| Filtering | Happens in memory | Happens in database |
| Performance | Slower for large data | Faster for large data |
| Query Translation | No | Yes (SQL generated) |
| Use Case | Collections | Database queries |
🔹 IEnumerable Example
var employees = context.Employees.ToList()
.Where(e => e.Salary > 50000);
What Happens?
-
ToList()→ Fetch ALL records from database -
Where()→ Filter in memory
👉 Database query:
SELECT * FROM Employees
👉 Filtering happens after data is loaded
❌ Bad for large data
🔹 IQueryable Example
var employees = context.Employees
.Where(e => e.Salary > 50000);
What Happens?
👉 SQL generated:
SELECT * FROM Employees WHERE Salary > 50000
👉 Filtering happens in database
✅ Much faster
🔹 Key Concept
IEnumerable
Database → All Data → Memory → Filter
IQueryable
Database → Filter → Only Needed Data → Memory
🔹 Performance Example
Imagine table has 1 million records
IEnumerable
-
Fetch 1 million records
-
Filter in memory
❌ Slow
❌ High memory usage
IQueryable
-
Fetch only filtered data
✅ Fast
✅ Less memory
🔹 Real World Example
IEnumerable<Employee> employees = context.Employees;
employees = employees.Where(x => x.Department == "IT");
👉 Fetch all records first
Better version:
IQueryable<Employee> employees = context.Employees;
employees = employees.Where(x => x.Department == "IT");
👉 Filtering in database
🔹 Interview One-Line Answer
IEnumerable executes query in memory, while IQueryable executes query in database.
🔹 Very Common Interview Question
Which is faster?
👉 IQueryable (for database queries)
🔹 When to Use What
Use IQueryable when:
-
Working with database
-
Using EF Core
-
Large data
Use IEnumerable when:
-
Working with in-memory collections
-
Small data
-
After data is already loaded
🔹 Interview Trick Question ⚡
What happens when you call ToList()?
context.Employees.ToList().Where(...)
👉 ToList() converts IQueryable → IEnumerable
After that:
👉 Filtering happens in memory
🔹 Example
var data = context.Employees
.Where(x => x.Age > 25)
.ToList();
Best Practice:
👉 Apply Where() before ToList()
