When working with LINQ in C#, two commonly used interfaces are IEnumerable and IQueryable. At first glance, they may look similar, but they serve different purposes and have a big impact on performance and where the query executes (in memory vs. database).
In this article, we’ll break down the difference with real examples, pros and cons, and when to use each.
🔹 What is IEnumerable?
-
Defined in
System.Collections
namespace. -
Works with in-memory collections like
List
,Array
,Dictionary
. -
Suitable for small datasets.
-
LINQ query executes in the application memory (after loading data).
Example of IEnumerable
✅ Here, filtering (n % 2 == 0
) happens inside the .NET process (in memory).
🔹 What is IQueryable?
-
Defined in
System.Linq
namespace. -
Works with remote data sources (SQL Server, Cosmos DB, MongoDB, etc.).
-
Suitable for large datasets.
-
LINQ query is converted into expression trees, then executed in the database.
Example of IQueryable (Entity Framework)
✅ Here, the filtering (s.Name.StartsWith("A")
) is converted into SQL and executed in the database.
🔹 Key Differences Between IEnumerable and IQueryable
Feature | IEnumerable | IQueryable |
---|---|---|
Namespace | System.Collections | System.Linq |
Execution | In-memory (LINQ to Objects) | Remote (LINQ to SQL, Cosmos DB, etc.) |
Performance | Loads all data, then filters | Filters at DB level → efficient |
Best For | Small in-memory collections | Large datasets from databases |
Deferred Execution | ✅ Yes | ✅ Yes |
Example Sources | List, Array, Dictionary | Entity Framework DbSet, ORM queries |
🔹 When to Use IEnumerable vs IQueryable
-
Use IEnumerable when:
-
Working with in-memory collections (
List
,Array
). -
Data set is small and already loaded.
-
You need LINQ to Objects queries.
-
-
Use IQueryable when:
-
Fetching data from a database or remote service.
-
You want to avoid loading the entire dataset into memory.
-
Filtering/sorting should happen at the source (SQL).
-
🔹 Final Thoughts
Both IEnumerable
and IQueryable
support deferred execution, but the key difference lies in where the query is executed.
-
IEnumerable
: query runs in memory → good for small collections. -
IQueryable
: query runs at the database/source → good for large datasets.
👉 As a best practice:
-
For Entity Framework or large data queries → use
IQueryable
. -
For small in-memory operations → use
IEnumerable
.
✅ Now you have a clear understanding of IEnumerable
vs IQueryable
with real-world .NET examples.