Sobes.tech
Senior

What is LINQ? What is the difference between IEnumerable and IQueryable?

sobes.tech AI

Answer from AI

LINQ (Language Integrated Query) is a technology in C# that allows writing queries to data collections directly in C# code using syntax similar to SQL. LINQ simplifies data handling, making the code more readable and expressive.

Difference between IEnumerable and IQueryable:

  • IEnumerable<T> is an interface for iterating over collections in memory. Queries to IEnumerable are executed in memory, meaning data is first loaded and then filtered or processed. Suitable for working with collections in RAM.

  • IQueryable<T> extends IEnumerable and allows building queries that can be translated into expressions executed on the data source side (e.g., in a database). Queries to IQueryable are deferred and executed on the server, which helps optimize data retrieval.

Example:

IQueryable<User> usersQuery = dbContext.Users.Where(u => u.Age > 18); // query to the database
var usersList = usersQuery.ToList(); // execute query and get data

IEnumerable<User> usersEnumerable = usersList.Where(u => u.IsActive); // in-memory filtering

Thus, IQueryable is efficient for building queries to remote data sources, while IEnumerable is suitable for working with already loaded collections.