DEV Community

Sardar Mudassar Ali Khan
Sardar Mudassar Ali Khan

Posted on • Edited on

IEnumerable Vs IQueryable in Asp.net Core Web API

In C#, the interfaces IEnumerable and IQueryable are both used to query and modify data. They do differ significantly in terms of their usage and behavior, though.
The underlying interface for all collections that can be enumerated is called IEnumerable. You may iterate over a collection using a foreach loop or LINQ query operators like "Where" and "Select" because it represents a forward-only cursor of elements. It is frequently applied to already-loaded data structures such as arrays, lists, and other in-memory collections. A number of methods, including GetEnumerator() and GetEnumeratorAsync(), are available in the IEnumerable interface to acquire an enumerator for traversing the collection.

Example:

IEnumerable<string> names = new List<string> { "John", "Jane", "Alice", "Bob" };

foreach (string name in names)
{
    Console.WriteLine(name);
}

// Output:
// John
// Jane
// Alice
// Bob
Enter fullscreen mode Exit fullscreen mode

The IQueryable interface, on the other hand, extends the IEnumerable interface and is used to query data from a data source, such as a database, utilizing query providers like LINQ to SQL or Entity Framework. It indicates a query whose execution is postponed until the query is materialized or enumerated. The underlying query provider can carry out query translation and optimization thanks to this deferred execution. IQueryable's support for LINQ expressions and query operators makes it possible to create sophisticated inquiries.

Example:

IQueryable<string> names = dbContext.Users.Where(u => u.Age > 18).Select(u => u.Name);

foreach (string name in names)
{
    Console.WriteLine(name);
}

// The actual query to the database is executed here, fetching only the required data
// Output:
// John
// Jane
// Alice
// ...
Enter fullscreen mode Exit fullscreen mode

An IQueryable representing a database table or queryable collection is dbContext.Users in the example above. The Where and Select operators are used in the LINQ query to filter and project the data. Whenever the foreach loop iterates through the "names" collection, the query is conducted, and data is retrieved from the database.
The primary distinction between IEnumerable and IQueryable is that IEnumerable is used for in-memory collections and executes in-memory operations, whereas IQueryable is used to query external data sources (such as databases) and supports query composition and deferred execution for the best possible performance.

Top comments (0)