In C#, both IEnumerable and IQueryable interfaces are used for querying collections of data, but they serve different purposes and have different capabilities. Here's a breakdown of the differences between them:
1. IEnumerable Interface in C#
- Defined in the
System.Collectionsnamespace. - Represents a forward-only cursor of elements in a collection.
- Suitable for querying in-memory collections such as arrays, lists, and other data structures that implement
IEnumerable. - Queries are executed on the client side, meaning all data is pulled into memory before applying the query operations.
- Provides basic querying capabilities such as filtering, projection, and sorting.
- LINQ queries
IEnumerableare evaluated using LINQ to Objects, working with objects in memory. - Supports deferred execution, meaning query operations are executed only when iterating over the result or calling terminal operations like
ToList()orCount().
Example
IEnumerable<int> numbers = new List<int> { 1, 2, 3, 4, 5 };
var query = numbers.Where(n => n % 2 == 0);
2. IQueryable Interface in C#
- Defined in the
System.Linqnamespace. - Inherits from
IEnumerableand extends its capabilities for querying data sources. - Represents a queryable data source that allows composing and executing queries against it.
- Suitable for querying external data sources such as databases, web services, or other data providers that support query execution.
- Supports more advanced querying capabilities compared to
IEnumerable, including composition of queries and expression trees. - Queries are typically translated into a query language specific to the data source (e.g., SQL for databases) and executed on the server side.
- Provides deferred execution, allowing query execution to be delayed until necessary.
- Offers better performance for querying large datasets as it leverages the capabilities of the underlying data provider for query execution.
Example
IQueryable<int> numbers = dbContext.Numbers;
var query = numbers.Where(n => n % 2 == 0);
Summary
IEnumerable is suitable for the basic querying of in-memory collections with client-side execution, while IQueryable is designed for querying external data sources with advanced capabilities and server-side execution. The choice between them depends on the nature of the data source and the complexity of the querying requirements.

Mariusz PostolPosted Mar 1, 2024, 10:13 AM
IEnumerable - in the attached example what is the value of the query variable after executing the expression of the assignment statement?
Mariusz PostolPosted Mar 1, 2024, 10:11 AM
IEnumerable - in the attached example you used var as the type of query variable. Is it an anonymous type? What is the practical reason to use var in a context similar to this?
Mariusz PostolPosted Mar 1, 2024, 10:04 AM
IEnumerable - what is the practical reason (benefit) to support deferred execution of expressions? Is it a goal or rather a side effect?